From c51e04c02941c6bcc96cf2d6bfc95483247e910c Mon Sep 17 00:00:00 2001 From: yoshi-automation Date: Sat, 1 Aug 2020 11:12:45 -0700 Subject: [PATCH 01/17] changes without context autosynth cannot find the source of changes triggered by earlier changes in this repository, or by version upgrades to tools such as linters. --- samples/snippets/noxfile.py | 26 ++++++++++++++------------ synth.metadata | 4 ++-- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/samples/snippets/noxfile.py b/samples/snippets/noxfile.py index 5660f08b..ba55d7ce 100644 --- a/samples/snippets/noxfile.py +++ b/samples/snippets/noxfile.py @@ -37,22 +37,24 @@ TEST_CONFIG = { # You can opt out from the test for specific Python versions. - "ignored_versions": ["2.7"], + 'ignored_versions': ["2.7"], + # An envvar key for determining the project id to use. Change it # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a # build specific Cloud project. You can also use your own string # to use your own Cloud project. - "gcloud_project_env": "GOOGLE_CLOUD_PROJECT", + 'gcloud_project_env': 'GOOGLE_CLOUD_PROJECT', # 'gcloud_project_env': 'BUILD_SPECIFIC_GCLOUD_PROJECT', + # A dictionary you want to inject into your test. Don't put any # secrets here. These values will override predefined values. - "envs": {}, + 'envs': {}, } try: # Ensure we can import noxfile_config in the project's directory. - sys.path.append(".") + sys.path.append('.') from noxfile_config import TEST_CONFIG_OVERRIDE except ImportError as e: print("No user noxfile_config found: detail: {}".format(e)) @@ -67,12 +69,12 @@ def get_pytest_env_vars(): ret = {} # Override the GCLOUD_PROJECT and the alias. - env_key = TEST_CONFIG["gcloud_project_env"] + env_key = TEST_CONFIG['gcloud_project_env'] # This should error out if not set. - ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] + ret['GOOGLE_CLOUD_PROJECT'] = os.environ[env_key] # Apply user supplied envs. - ret.update(TEST_CONFIG["envs"]) + ret.update(TEST_CONFIG['envs']) return ret @@ -81,7 +83,7 @@ def get_pytest_env_vars(): ALL_VERSIONS = ["2.7", "3.6", "3.7", "3.8"] # Any default versions that should be ignored. -IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] +IGNORED_VERSIONS = TEST_CONFIG['ignored_versions'] TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) @@ -136,7 +138,7 @@ def lint(session): args = FLAKE8_COMMON_ARGS + [ "--application-import-names", ",".join(local_names), - ".", + "." ] session.run("flake8", *args) @@ -180,9 +182,9 @@ def py(session): if session.python in TESTED_VERSIONS: _session_tests(session) else: - session.skip( - "SKIPPED: {} tests are disabled for this sample.".format(session.python) - ) + session.skip("SKIPPED: {} tests are disabled for this sample.".format( + session.python + )) # diff --git a/synth.metadata b/synth.metadata index c9656a59..f20df11e 100644 --- a/synth.metadata +++ b/synth.metadata @@ -3,8 +3,8 @@ { "git": { "name": ".", - "remote": "git@github.com:googleapis/python-securitycenter.git", - "sha": "a30a996cafb8dd9fed3c86ef641d42ab959febe3" + "remote": "https://github.com/googleapis/python-securitycenter.git", + "sha": "c70d7904425ae5ac252ffa7317ec6d08234a6c27" } }, { From 4281f287e53ad56ea81386a665fc96e536186850 Mon Sep 17 00:00:00 2001 From: yoshi-automation Date: Sat, 1 Aug 2020 11:17:01 -0700 Subject: [PATCH 02/17] fix: migrate securitycenter/v1p1beta1 to grpc_service_config PiperOrigin-RevId: 321179822 Source-Author: Google APIs Source-Date: Tue Jul 14 10:04:21 2020 -0700 Source-Repo: googleapis/googleapis Source-Sha: afa7f44f57e6ac33cf060d1764c9940dd404f725 Source-Link: https://github.com/googleapis/googleapis/commit/afa7f44f57e6ac33cf060d1764c9940dd404f725 --- .../gapic/security_center_client_config.py | 155 +++++++++++------- synth.metadata | 4 +- 2 files changed, 99 insertions(+), 60 deletions(-) diff --git a/google/cloud/securitycenter_v1p1beta1/gapic/security_center_client_config.py b/google/cloud/securitycenter_v1p1beta1/gapic/security_center_client_config.py index 975998d8..1f6297b6 100644 --- a/google/cloud/securitycenter_v1p1beta1/gapic/security_center_client_config.py +++ b/google/cloud/securitycenter_v1p1beta1/gapic/security_center_client_config.py @@ -2,135 +2,174 @@ "interfaces": { "google.cloud.securitycenter.v1p1beta1.SecurityCenter": { "retry_codes": { - "idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "non_idempotent": [], + "retry_policy_1_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], + "no_retry_2_codes": [], + "no_retry_codes": [], + "retry_policy_2_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], + "no_retry_1_codes": [], }, "retry_params": { - "default": { + "retry_policy_1_params": { "initial_retry_delay_millis": 100, "retry_delay_multiplier": 1.3, "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 20000, + "initial_rpc_timeout_millis": 60000, "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 20000, - "total_timeout_millis": 600000, - } + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 60000, + }, + "retry_policy_2_params": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 480000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 480000, + "total_timeout_millis": 480000, + }, + "no_retry_params": { + "initial_retry_delay_millis": 0, + "retry_delay_multiplier": 0.0, + "max_retry_delay_millis": 0, + "initial_rpc_timeout_millis": 0, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 0, + "total_timeout_millis": 0, + }, + "no_retry_1_params": { + "initial_retry_delay_millis": 0, + "retry_delay_multiplier": 0.0, + "max_retry_delay_millis": 0, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 60000, + }, + "no_retry_2_params": { + "initial_retry_delay_millis": 0, + "retry_delay_multiplier": 0.0, + "max_retry_delay_millis": 0, + "initial_rpc_timeout_millis": 480000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 480000, + "total_timeout_millis": 480000, + }, }, "methods": { "CreateSource": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "CreateFinding": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "CreateNotificationConfig": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "DeleteNotificationConfig": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "GetIamPolicy": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "GetNotificationConfig": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "GetOrganizationSettings": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "GetSource": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "GroupAssets": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "timeout_millis": 480000, + "retry_codes_name": "retry_policy_2_codes", + "retry_params_name": "retry_policy_2_params", }, "GroupFindings": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "timeout_millis": 480000, + "retry_codes_name": "retry_policy_2_codes", + "retry_params_name": "retry_policy_2_params", }, "ListAssets": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "timeout_millis": 480000, + "retry_codes_name": "retry_policy_2_codes", + "retry_params_name": "retry_policy_2_params", }, "ListFindings": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "timeout_millis": 480000, + "retry_codes_name": "retry_policy_2_codes", + "retry_params_name": "retry_policy_2_params", }, "ListNotificationConfigs": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "ListSources": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "RunAssetDiscovery": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "SetFindingState": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "SetIamPolicy": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "TestIamPermissions": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "UpdateFinding": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "UpdateNotificationConfig": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "UpdateOrganizationSettings": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "UpdateSource": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "UpdateSecurityMarks": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "timeout_millis": 480000, + "retry_codes_name": "no_retry_2_codes", + "retry_params_name": "no_retry_2_params", }, }, } diff --git a/synth.metadata b/synth.metadata index f20df11e..bf3edc49 100644 --- a/synth.metadata +++ b/synth.metadata @@ -11,8 +11,8 @@ "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "50ae1c72fd94a3ae4269394b09e4b7fbb9251146", - "internalRef": "320484049" + "sha": "afa7f44f57e6ac33cf060d1764c9940dd404f725", + "internalRef": "321179822" } }, { From fe6e16bc91c6baa87b941bfd7b7a3c97b18a4500 Mon Sep 17 00:00:00 2001 From: yoshi-automation Date: Sat, 1 Aug 2020 11:17:31 -0700 Subject: [PATCH 03/17] fix: migrate securitycenter/v1 to grpc_service_config PiperOrigin-RevId: 321179885 Source-Author: Google APIs Source-Date: Tue Jul 14 10:04:39 2020 -0700 Source-Repo: googleapis/googleapis Source-Sha: 9362f58401cfe3b463b75a18d134bb818ad4dcb2 Source-Link: https://github.com/googleapis/googleapis/commit/9362f58401cfe3b463b75a18d134bb818ad4dcb2 --- .../gapic/security_center_client.py | 1268 ++++++++--------- .../gapic/security_center_client_config.py | 169 ++- .../security_center_grpc_transport.py | 114 +- synth.metadata | 4 +- .../v1/test_security_center_client_v1.py | 380 ++--- 5 files changed, 987 insertions(+), 948 deletions(-) diff --git a/google/cloud/securitycenter_v1/gapic/security_center_client.py b/google/cloud/securitycenter_v1/gapic/security_center_client.py index 9c1f9104..e6c19fcd 100644 --- a/google/cloud/securitycenter_v1/gapic/security_center_client.py +++ b/google/cloud/securitycenter_v1/gapic/security_center_client.py @@ -282,35 +282,37 @@ def __init__( self._inner_api_calls = {} # Service calls - def get_iam_policy( + def create_source( self, - resource, - options_=None, + parent, + source, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ - Gets the access control policy on the specified Source. + Creates a source. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> - >>> # TODO: Initialize `resource`: - >>> resource = '' + >>> parent = client.organization_path('[ORGANIZATION]') >>> - >>> response = client.get_iam_policy(resource) + >>> # TODO: Initialize `source`: + >>> source = {} + >>> + >>> response = client.create_source(parent, source) Args: - resource (str): REQUIRED: The resource for which the policy is being requested. - See the operation documentation for the appropriate value for this field. - options_ (Union[dict, ~google.cloud.securitycenter_v1.types.GetPolicyOptions]): OPTIONAL: A ``GetPolicyOptions`` object for specifying options to - ``GetIamPolicy``. This field is only used by Cloud IAM. + parent (str): Required. Resource name of the new source's parent. Its format + should be "organizations/[organization_id]". + source (Union[dict, ~google.cloud.securitycenter_v1.types.Source]): Required. The Source being created, only the display_name and + description will be used. All other fields will be ignored. If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.GetPolicyOptions` + message :class:`~google.cloud.securitycenter_v1.types.Source` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -321,7 +323,7 @@ def get_iam_policy( that is provided to the method. Returns: - A :class:`~google.cloud.securitycenter_v1.types.Policy` instance. + A :class:`~google.cloud.securitycenter_v1.types.Source` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request @@ -331,24 +333,24 @@ def get_iam_policy( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "get_iam_policy" not in self._inner_api_calls: + if "create_source" not in self._inner_api_calls: self._inner_api_calls[ - "get_iam_policy" + "create_source" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_iam_policy, - default_retry=self._method_configs["GetIamPolicy"].retry, - default_timeout=self._method_configs["GetIamPolicy"].timeout, + self.transport.create_source, + default_retry=self._method_configs["CreateSource"].retry, + default_timeout=self._method_configs["CreateSource"].timeout, client_info=self._client_info, ) - request = iam_policy_pb2.GetIamPolicyRequest( - resource=resource, options=options_, + request = securitycenter_service_pb2.CreateSourceRequest( + parent=parent, source=source, ) if metadata is None: metadata = [] metadata = list(metadata) try: - routing_header = [("resource", resource)] + routing_header = [("parent", parent)] except AttributeError: pass else: @@ -357,186 +359,49 @@ def get_iam_policy( ) metadata.append(routing_metadata) - return self._inner_api_calls["get_iam_policy"]( + return self._inner_api_calls["create_source"]( request, retry=retry, timeout=timeout, metadata=metadata ) - def group_assets( + def create_finding( self, parent, - group_by, - filter_=None, - compare_duration=None, - read_time=None, - page_size=None, + finding_id, + finding, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ - Filters an organization's assets and groups them by their specified - properties. + Creates a finding. The corresponding source must exist for finding creation + to succeed. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> - >>> parent = client.organization_path('[ORGANIZATION]') - >>> - >>> # TODO: Initialize `group_by`: - >>> group_by = '' - >>> - >>> # Iterate over all results - >>> for element in client.group_assets(parent, group_by): - ... # process element - ... pass + >>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]') >>> + >>> # TODO: Initialize `finding_id`: + >>> finding_id = '' >>> - >>> # Alternatively: + >>> # TODO: Initialize `finding`: + >>> finding = {} >>> - >>> # Iterate over results one page at a time - >>> for page in client.group_assets(parent, group_by).pages: - ... for element in page: - ... # process element - ... pass + >>> response = client.create_finding(parent, finding_id, finding) Args: - parent (str): Required. Name of the organization to groupBy. Its format is - "organizations/[organization_id]". - group_by (str): Required. Expression that defines what assets fields to use for - grouping. The string value should follow SQL syntax: comma separated - list of fields. For example: - "security_center_properties.resource_project,security_center_properties.project". - - The following fields are supported when compare_duration is not set: - - - security_center_properties.resource_project - - security_center_properties.resource_project_display_name - - security_center_properties.resource_type - - security_center_properties.resource_parent - - security_center_properties.resource_parent_display_name - - The following fields are supported when compare_duration is set: - - - security_center_properties.resource_type - - security_center_properties.resource_project_display_name - - security_center_properties.resource_parent_display_name - filter_ (str): Expression that defines the filter to apply across assets. The - expression is a list of zero or more restrictions combined via logical - operators ``AND`` and ``OR``. Parentheses are supported, and ``OR`` has - higher precedence than ``AND``. - - Restrictions have the form `` `` and may have a - ``-`` character in front of them to indicate negation. The fields map to - those defined in the Asset resource. Examples include: - - - name - - security_center_properties.resource_name - - resource_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an RFC3339 string. - Examples: ``update_time = "2019-06-10T16:07:18-07:00"`` - ``update_time = 1560208038000`` - - - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an RFC3339 string. - Examples: ``create_time = "2019-06-10T16:07:18-07:00"`` - ``create_time = 1560208038000`` - - - iam_policy.policy_blob: ``=``, ``:`` - - - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, ``<=`` - - - security_marks.marks: ``=``, ``:`` - - - security_center_properties.resource_name: ``=``, ``:`` - - - security_center_properties.resource_display_name: ``=``, ``:`` - - - security_center_properties.resource_type: ``=``, ``:`` - - - security_center_properties.resource_parent: ``=``, ``:`` - - - security_center_properties.resource_parent_display_name: ``=``, ``:`` - - - security_center_properties.resource_project: ``=``, ``:`` - - - security_center_properties.resource_project_display_name: ``=``, - ``:`` - - - security_center_properties.resource_owners: ``=``, ``:`` - - For example, ``resource_properties.size = 100`` is a valid filter - string. - - Use a partial match on the empty string to filter based on a property - existing:\ ``resource_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter based on a - property not existing: ``-resource_properties.my_property : ""`` - compare_duration (Union[dict, ~google.cloud.securitycenter_v1.types.Duration]): When compare_duration is set, the GroupResult's "state_change" - property is updated to indicate whether the asset was added, removed, or - remained present during the compare_duration period of time that - precedes the read_time. This is the time between (read_time - - compare_duration) and read_time. - - The state change value is derived based on the presence of the asset at - the two points in time. Intermediate state changes between the two times - don't affect the result. For example, the results aren't affected if the - asset is removed and re-created again. - - Possible "state_change" values when compare_duration is specified: - - - "ADDED": indicates that the asset was not present at the start of - compare_duration, but present at reference_time. - - "REMOVED": indicates that the asset was present at the start of - compare_duration, but not present at reference_time. - - "ACTIVE": indicates that the asset was present at both the start and - the end of the time period defined by compare_duration and - reference_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set for all - assets present at read_time. - - If this field is set then ``state_change`` must be a specified field in - ``group_by``. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Duration` - read_time (Union[dict, ~google.cloud.securitycenter_v1.types.Timestamp]): Time used as a reference point when filtering assets. The filter is limited - to assets existing at the supplied time and their values are those at that - specific time. Absence of this field will default to the API's version of - NOW. + parent (str): Required. Resource name of the new finding's parent. Its format + should be "organizations/[organization_id]/sources/[source_id]". + finding_id (str): Required. Unique identifier provided by the client within the parent scope. + It must be alphanumeric and less than or equal to 32 characters and + greater than 0 characters in length. + finding (Union[dict, ~google.cloud.securitycenter_v1.types.Finding]): Required. The Finding being created. The name and security_marks + will be ignored as they are both output only fields on this resource. If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Timestamp` - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. + message :class:`~google.cloud.securitycenter_v1.types.Finding` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -547,10 +412,7 @@ def group_assets( that is provided to the method. Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.securitycenter_v1.types.GroupResult` instances. - You can also iterate over the pages of the response - using its `pages` property. + A :class:`~google.cloud.securitycenter_v1.types.Finding` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request @@ -560,23 +422,18 @@ def group_assets( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "group_assets" not in self._inner_api_calls: + if "create_finding" not in self._inner_api_calls: self._inner_api_calls[ - "group_assets" + "create_finding" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.group_assets, - default_retry=self._method_configs["GroupAssets"].retry, - default_timeout=self._method_configs["GroupAssets"].timeout, + self.transport.create_finding, + default_retry=self._method_configs["CreateFinding"].retry, + default_timeout=self._method_configs["CreateFinding"].timeout, client_info=self._client_info, ) - request = securitycenter_service_pb2.GroupAssetsRequest( - parent=parent, - group_by=group_by, - filter=filter_, - compare_duration=compare_duration, - read_time=read_time, - page_size=page_size, + request = securitycenter_service_pb2.CreateFindingRequest( + parent=parent, finding_id=finding_id, finding=finding, ) if metadata is None: metadata = [] @@ -591,187 +448,50 @@ def group_assets( ) metadata.append(routing_metadata) - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["group_assets"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="group_by_results", - request_token_field="page_token", - response_token_field="next_page_token", + return self._inner_api_calls["create_finding"]( + request, retry=retry, timeout=timeout, metadata=metadata ) - return iterator - def group_findings( + def create_notification_config( self, parent, - group_by, - filter_=None, - read_time=None, - compare_duration=None, - page_size=None, + config_id, + notification_config, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. Example: - /v1/organizations/{organization_id}/sources/-/findings + Creates a notification config. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> - >>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]') - >>> - >>> # TODO: Initialize `group_by`: - >>> group_by = '' - >>> - >>> # Iterate over all results - >>> for element in client.group_findings(parent, group_by): - ... # process element - ... pass + >>> parent = client.organization_path('[ORGANIZATION]') >>> + >>> # TODO: Initialize `config_id`: + >>> config_id = '' >>> - >>> # Alternatively: + >>> # TODO: Initialize `notification_config`: + >>> notification_config = {} >>> - >>> # Iterate over results one page at a time - >>> for page in client.group_findings(parent, group_by).pages: - ... for element in page: - ... # process element - ... pass + >>> response = client.create_notification_config(parent, config_id, notification_config) Args: - parent (str): Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]". To groupBy across - all sources provide a source_id of ``-``. For example: - organizations/{organization_id}/sources/- - group_by (str): Required. Expression that defines what assets fields to use for - grouping (including ``state_change``). The string value should follow - SQL syntax: comma separated list of fields. For example: - "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - - The following fields are supported when compare_duration is set: - - - state_change - filter_ (str): Expression that defines the filter to apply across findings. The - expression is a list of one or more restrictions combined via logical - operators ``AND`` and ``OR``. Parentheses are supported, and ``OR`` has - higher precedence than ``AND``. - - Restrictions have the form `` `` and may have a - ``-`` character in front of them to indicate negation. Examples include: - - - name - - source_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - parent: ``=``, ``:`` - - - resource_name: ``=``, ``:`` - - - state: ``=``, ``:`` - - - category: ``=``, ``:`` - - - external_uri: ``=``, ``:`` - - - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an RFC3339 string. - Examples: ``event_time = "2019-06-10T16:07:18-07:00"`` - ``event_time = 1560208038000`` - - - security_marks.marks: ``=``, ``:`` - - - source_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, ``<=`` - - For example, ``source_properties.size = 100`` is a valid filter string. - - Use a partial match on the empty string to filter based on a property - existing: ``source_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter based on a - property not existing: ``-source_properties.my_property : ""`` - read_time (Union[dict, ~google.cloud.securitycenter_v1.types.Timestamp]): Time used as a reference point when filtering findings. The filter is - limited to findings existing at the supplied time and their values are - those at that specific time. Absence of this field will default to the - API's version of NOW. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Timestamp` - compare_duration (Union[dict, ~google.cloud.securitycenter_v1.types.Duration]): When compare_duration is set, the GroupResult's "state_change" - attribute is updated to indicate whether the finding had its state - changed, the finding's state remained unchanged, or if the finding was - added during the compare_duration period of time that precedes the - read_time. This is the time between (read_time - compare_duration) and - read_time. - - The state_change value is derived based on the presence and state of the - finding at the two points in time. Intermediate state changes between - the two times don't affect the result. For example, the results aren't - affected if the finding is made inactive and then active again. - - Possible "state_change" values when compare_duration is specified: - - - "CHANGED": indicates that the finding was present and matched the - given filter at the start of compare_duration, but changed its state - at read_time. - - "UNCHANGED": indicates that the finding was present and matched the - given filter at the start of compare_duration and did not change - state at read_time. - - "ADDED": indicates that the finding did not match the given filter or - was not present at the start of compare_duration, but was present at - read_time. - - "REMOVED": indicates that the finding was present and matched the - filter at the start of compare_duration, but did not match the filter - at read_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set for all - findings present at read_time. - - If this field is set then ``state_change`` must be a specified field in - ``group_by``. + parent (str): Required. Resource name of the new notification config's parent. Its + format is "organizations/[organization_id]". + config_id (str): Required. + Unique identifier provided by the client within the parent scope. + It must be between 1 and 128 characters, and contains alphanumeric + characters, underscores or hyphens only. + notification_config (Union[dict, ~google.cloud.securitycenter_v1.types.NotificationConfig]): Required. The notification config being created. The name and the service + account will be ignored as they are both output only fields on this + resource. If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Duration` - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. + message :class:`~google.cloud.securitycenter_v1.types.NotificationConfig` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -782,10 +502,7 @@ def group_findings( that is provided to the method. Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.securitycenter_v1.types.GroupResult` instances. - You can also iterate over the pages of the response - using its `pages` property. + A :class:`~google.cloud.securitycenter_v1.types.NotificationConfig` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request @@ -795,23 +512,20 @@ def group_findings( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "group_findings" not in self._inner_api_calls: + if "create_notification_config" not in self._inner_api_calls: self._inner_api_calls[ - "group_findings" + "create_notification_config" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.group_findings, - default_retry=self._method_configs["GroupFindings"].retry, - default_timeout=self._method_configs["GroupFindings"].timeout, + self.transport.create_notification_config, + default_retry=self._method_configs["CreateNotificationConfig"].retry, + default_timeout=self._method_configs[ + "CreateNotificationConfig" + ].timeout, client_info=self._client_info, ) - request = securitycenter_service_pb2.GroupFindingsRequest( - parent=parent, - group_by=group_by, - filter=filter_, - read_time=read_time, - compare_duration=compare_duration, - page_size=page_size, + request = securitycenter_service_pb2.CreateNotificationConfigRequest( + parent=parent, config_id=config_id, notification_config=notification_config, ) if metadata is None: metadata = [] @@ -826,52 +540,32 @@ def group_findings( ) metadata.append(routing_metadata) - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["group_findings"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="group_by_results", - request_token_field="page_token", - response_token_field="next_page_token", + return self._inner_api_calls["create_notification_config"]( + request, retry=retry, timeout=timeout, metadata=metadata ) - return iterator - def test_iam_permissions( + def delete_notification_config( self, - resource, - permissions, + name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ - Returns the permissions that a caller has on the specified source. + Deletes a notification config. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> - >>> # TODO: Initialize `resource`: - >>> resource = '' - >>> - >>> # TODO: Initialize `permissions`: - >>> permissions = [] + >>> name = client.notification_config_path('[ORGANIZATION]', '[NOTIFICATION_CONFIG]') >>> - >>> response = client.test_iam_permissions(resource, permissions) + >>> client.delete_notification_config(name) Args: - resource (str): REQUIRED: The resource for which the policy detail is being requested. - See the operation documentation for the appropriate value for this field. - permissions (list[str]): The set of permissions to check for the ``resource``. Permissions - with wildcards (such as '*' or 'storage.*') are not allowed. For more - information see `IAM - Overview `__. + name (str): Required. Name of the notification config to delete. Its format is + "organizations/[organization_id]/notificationConfigs/[config_id]". retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -881,9 +575,6 @@ def test_iam_permissions( metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. - Returns: - A :class:`~google.cloud.securitycenter_v1.types.TestIamPermissionsResponse` instance. - Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. @@ -892,24 +583,24 @@ def test_iam_permissions( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "test_iam_permissions" not in self._inner_api_calls: + if "delete_notification_config" not in self._inner_api_calls: self._inner_api_calls[ - "test_iam_permissions" + "delete_notification_config" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.test_iam_permissions, - default_retry=self._method_configs["TestIamPermissions"].retry, - default_timeout=self._method_configs["TestIamPermissions"].timeout, + self.transport.delete_notification_config, + default_retry=self._method_configs["DeleteNotificationConfig"].retry, + default_timeout=self._method_configs[ + "DeleteNotificationConfig" + ].timeout, client_info=self._client_info, ) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource=resource, permissions=permissions, - ) + request = securitycenter_service_pb2.DeleteNotificationConfigRequest(name=name,) if metadata is None: metadata = [] metadata = list(metadata) try: - routing_header = [("resource", resource)] + routing_header = [("name", name)] except AttributeError: pass else: @@ -918,41 +609,39 @@ def test_iam_permissions( ) metadata.append(routing_metadata) - return self._inner_api_calls["test_iam_permissions"]( + self._inner_api_calls["delete_notification_config"]( request, retry=retry, timeout=timeout, metadata=metadata ) - def create_source( + def get_iam_policy( self, - parent, - source, + resource, + options_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ - Creates a source. + Gets the access control policy on the specified Source. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> - >>> parent = client.organization_path('[ORGANIZATION]') - >>> - >>> # TODO: Initialize `source`: - >>> source = {} + >>> # TODO: Initialize `resource`: + >>> resource = '' >>> - >>> response = client.create_source(parent, source) + >>> response = client.get_iam_policy(resource) Args: - parent (str): Required. Resource name of the new source's parent. Its format - should be "organizations/[organization_id]". - source (Union[dict, ~google.cloud.securitycenter_v1.types.Source]): Required. The Source being created, only the display_name and - description will be used. All other fields will be ignored. + resource (str): REQUIRED: The resource for which the policy is being requested. + See the operation documentation for the appropriate value for this field. + options_ (Union[dict, ~google.cloud.securitycenter_v1.types.GetPolicyOptions]): OPTIONAL: A ``GetPolicyOptions`` object for specifying options to + ``GetIamPolicy``. This field is only used by Cloud IAM. If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Source` + message :class:`~google.cloud.securitycenter_v1.types.GetPolicyOptions` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -963,7 +652,7 @@ def create_source( that is provided to the method. Returns: - A :class:`~google.cloud.securitycenter_v1.types.Source` instance. + A :class:`~google.cloud.securitycenter_v1.types.Policy` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request @@ -973,24 +662,24 @@ def create_source( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "create_source" not in self._inner_api_calls: + if "get_iam_policy" not in self._inner_api_calls: self._inner_api_calls[ - "create_source" + "get_iam_policy" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_source, - default_retry=self._method_configs["CreateSource"].retry, - default_timeout=self._method_configs["CreateSource"].timeout, + self.transport.get_iam_policy, + default_retry=self._method_configs["GetIamPolicy"].retry, + default_timeout=self._method_configs["GetIamPolicy"].timeout, client_info=self._client_info, ) - request = securitycenter_service_pb2.CreateSourceRequest( - parent=parent, source=source, + request = iam_policy_pb2.GetIamPolicyRequest( + resource=resource, options=options_, ) if metadata is None: metadata = [] metadata = list(metadata) try: - routing_header = [("parent", parent)] + routing_header = [("resource", resource)] except AttributeError: pass else: @@ -999,49 +688,32 @@ def create_source( ) metadata.append(routing_metadata) - return self._inner_api_calls["create_source"]( + return self._inner_api_calls["get_iam_policy"]( request, retry=retry, timeout=timeout, metadata=metadata ) - def create_finding( + def get_notification_config( self, - parent, - finding_id, - finding, + name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ - Creates a finding. The corresponding source must exist for finding creation - to succeed. + Gets a notification config. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> - >>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]') - >>> - >>> # TODO: Initialize `finding_id`: - >>> finding_id = '' - >>> - >>> # TODO: Initialize `finding`: - >>> finding = {} + >>> name = client.notification_config_path('[ORGANIZATION]', '[NOTIFICATION_CONFIG]') >>> - >>> response = client.create_finding(parent, finding_id, finding) + >>> response = client.get_notification_config(name) Args: - parent (str): Required. Resource name of the new finding's parent. Its format - should be "organizations/[organization_id]/sources/[source_id]". - finding_id (str): Required. Unique identifier provided by the client within the parent scope. - It must be alphanumeric and less than or equal to 32 characters and - greater than 0 characters in length. - finding (Union[dict, ~google.cloud.securitycenter_v1.types.Finding]): Required. The Finding being created. The name and security_marks - will be ignored as they are both output only fields on this resource. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Finding` + name (str): Required. Name of the notification config to get. Its format is + "organizations/[organization_id]/notificationConfigs/[config_id]". retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -1052,7 +724,7 @@ def create_finding( that is provided to the method. Returns: - A :class:`~google.cloud.securitycenter_v1.types.Finding` instance. + A :class:`~google.cloud.securitycenter_v1.types.NotificationConfig` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request @@ -1062,24 +734,22 @@ def create_finding( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "create_finding" not in self._inner_api_calls: + if "get_notification_config" not in self._inner_api_calls: self._inner_api_calls[ - "create_finding" + "get_notification_config" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_finding, - default_retry=self._method_configs["CreateFinding"].retry, - default_timeout=self._method_configs["CreateFinding"].timeout, + self.transport.get_notification_config, + default_retry=self._method_configs["GetNotificationConfig"].retry, + default_timeout=self._method_configs["GetNotificationConfig"].timeout, client_info=self._client_info, ) - request = securitycenter_service_pb2.CreateFindingRequest( - parent=parent, finding_id=finding_id, finding=finding, - ) + request = securitycenter_service_pb2.GetNotificationConfigRequest(name=name,) if metadata is None: metadata = [] metadata = list(metadata) try: - routing_header = [("parent", parent)] + routing_header = [("name", name)] except AttributeError: pass else: @@ -1088,50 +758,32 @@ def create_finding( ) metadata.append(routing_metadata) - return self._inner_api_calls["create_finding"]( + return self._inner_api_calls["get_notification_config"]( request, retry=retry, timeout=timeout, metadata=metadata ) - def create_notification_config( + def get_organization_settings( self, - parent, - config_id, - notification_config, + name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ - Creates a notification config. + Gets the settings for an organization. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> - >>> parent = client.organization_path('[ORGANIZATION]') - >>> - >>> # TODO: Initialize `config_id`: - >>> config_id = '' - >>> - >>> # TODO: Initialize `notification_config`: - >>> notification_config = {} + >>> name = client.organization_settings_path('[ORGANIZATION]') >>> - >>> response = client.create_notification_config(parent, config_id, notification_config) + >>> response = client.get_organization_settings(name) Args: - parent (str): Required. Resource name of the new notification config's parent. Its - format is "organizations/[organization_id]". - config_id (str): Required. - Unique identifier provided by the client within the parent scope. - It must be between 1 and 128 characters, and contains alphanumeric - characters, underscores or hyphens only. - notification_config (Union[dict, ~google.cloud.securitycenter_v1.types.NotificationConfig]): Required. The notification config being created. The name and the service - account will be ignored as they are both output only fields on this - resource. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.NotificationConfig` + name (str): Required. Name of the organization to get organization settings for. + Its format is "organizations/[organization_id]/organizationSettings". retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -1142,7 +794,7 @@ def create_notification_config( that is provided to the method. Returns: - A :class:`~google.cloud.securitycenter_v1.types.NotificationConfig` instance. + A :class:`~google.cloud.securitycenter_v1.types.OrganizationSettings` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request @@ -1152,26 +804,22 @@ def create_notification_config( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "create_notification_config" not in self._inner_api_calls: + if "get_organization_settings" not in self._inner_api_calls: self._inner_api_calls[ - "create_notification_config" + "get_organization_settings" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_notification_config, - default_retry=self._method_configs["CreateNotificationConfig"].retry, - default_timeout=self._method_configs[ - "CreateNotificationConfig" - ].timeout, + self.transport.get_organization_settings, + default_retry=self._method_configs["GetOrganizationSettings"].retry, + default_timeout=self._method_configs["GetOrganizationSettings"].timeout, client_info=self._client_info, ) - request = securitycenter_service_pb2.CreateNotificationConfigRequest( - parent=parent, config_id=config_id, notification_config=notification_config, - ) + request = securitycenter_service_pb2.GetOrganizationSettingsRequest(name=name,) if metadata is None: metadata = [] metadata = list(metadata) try: - routing_header = [("parent", parent)] + routing_header = [("name", name)] except AttributeError: pass else: @@ -1180,11 +828,11 @@ def create_notification_config( ) metadata.append(routing_metadata) - return self._inner_api_calls["create_notification_config"]( + return self._inner_api_calls["get_organization_settings"]( request, retry=retry, timeout=timeout, metadata=metadata ) - def delete_notification_config( + def get_source( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, @@ -1192,20 +840,20 @@ def delete_notification_config( metadata=None, ): """ - Deletes a notification config. + Gets a source. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> - >>> name = client.notification_config_path('[ORGANIZATION]', '[NOTIFICATION_CONFIG]') + >>> name = client.source_path('[ORGANIZATION]', '[SOURCE]') >>> - >>> client.delete_notification_config(name) + >>> response = client.get_source(name) Args: - name (str): Required. Name of the notification config to delete. Its format is - "organizations/[organization_id]/notificationConfigs/[config_id]". + name (str): Required. Relative resource name of the source. Its format is + "organizations/[organization_id]/source/[source_id]". retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -1215,6 +863,9 @@ def delete_notification_config( metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. + Returns: + A :class:`~google.cloud.securitycenter_v1.types.Source` instance. + Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. @@ -1223,19 +874,17 @@ def delete_notification_config( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "delete_notification_config" not in self._inner_api_calls: + if "get_source" not in self._inner_api_calls: self._inner_api_calls[ - "delete_notification_config" + "get_source" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.delete_notification_config, - default_retry=self._method_configs["DeleteNotificationConfig"].retry, - default_timeout=self._method_configs[ - "DeleteNotificationConfig" - ].timeout, + self.transport.get_source, + default_retry=self._method_configs["GetSource"].retry, + default_timeout=self._method_configs["GetSource"].timeout, client_info=self._client_info, ) - request = securitycenter_service_pb2.DeleteNotificationConfigRequest(name=name,) + request = securitycenter_service_pb2.GetSourceRequest(name=name,) if metadata is None: metadata = [] metadata = list(metadata) @@ -1249,32 +898,186 @@ def delete_notification_config( ) metadata.append(routing_metadata) - self._inner_api_calls["delete_notification_config"]( + return self._inner_api_calls["get_source"]( request, retry=retry, timeout=timeout, metadata=metadata ) - def get_notification_config( + def group_assets( self, - name, + parent, + group_by, + filter_=None, + compare_duration=None, + read_time=None, + page_size=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ - Gets a notification config. + Filters an organization's assets and groups them by their specified + properties. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> - >>> name = client.notification_config_path('[ORGANIZATION]', '[NOTIFICATION_CONFIG]') + >>> parent = client.organization_path('[ORGANIZATION]') >>> - >>> response = client.get_notification_config(name) + >>> # TODO: Initialize `group_by`: + >>> group_by = '' + >>> + >>> # Iterate over all results + >>> for element in client.group_assets(parent, group_by): + ... # process element + ... pass + >>> + >>> + >>> # Alternatively: + >>> + >>> # Iterate over results one page at a time + >>> for page in client.group_assets(parent, group_by).pages: + ... for element in page: + ... # process element + ... pass Args: - name (str): Required. Name of the notification config to get. Its format is - "organizations/[organization_id]/notificationConfigs/[config_id]". + parent (str): Required. Name of the organization to groupBy. Its format is + "organizations/[organization_id]". + group_by (str): Required. Expression that defines what assets fields to use for + grouping. The string value should follow SQL syntax: comma separated + list of fields. For example: + "security_center_properties.resource_project,security_center_properties.project". + + The following fields are supported when compare_duration is not set: + + - security_center_properties.resource_project + - security_center_properties.resource_project_display_name + - security_center_properties.resource_type + - security_center_properties.resource_parent + - security_center_properties.resource_parent_display_name + + The following fields are supported when compare_duration is set: + + - security_center_properties.resource_type + - security_center_properties.resource_project_display_name + - security_center_properties.resource_parent_display_name + filter_ (str): Expression that defines the filter to apply across assets. The + expression is a list of zero or more restrictions combined via logical + operators ``AND`` and ``OR``. Parentheses are supported, and ``OR`` has + higher precedence than ``AND``. + + Restrictions have the form `` `` and may have a + ``-`` character in front of them to indicate negation. The fields map to + those defined in the Asset resource. Examples include: + + - name + - security_center_properties.resource_name + - resource_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an RFC3339 string. + Examples: ``update_time = "2019-06-10T16:07:18-07:00"`` + ``update_time = 1560208038000`` + + - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an RFC3339 string. + Examples: ``create_time = "2019-06-10T16:07:18-07:00"`` + ``create_time = 1560208038000`` + + - iam_policy.policy_blob: ``=``, ``:`` + + - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, ``<=`` + + - security_marks.marks: ``=``, ``:`` + + - security_center_properties.resource_name: ``=``, ``:`` + + - security_center_properties.resource_display_name: ``=``, ``:`` + + - security_center_properties.resource_type: ``=``, ``:`` + + - security_center_properties.resource_parent: ``=``, ``:`` + + - security_center_properties.resource_parent_display_name: ``=``, ``:`` + + - security_center_properties.resource_project: ``=``, ``:`` + + - security_center_properties.resource_project_display_name: ``=``, + ``:`` + + - security_center_properties.resource_owners: ``=``, ``:`` + + For example, ``resource_properties.size = 100`` is a valid filter + string. + + Use a partial match on the empty string to filter based on a property + existing:\ ``resource_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter based on a + property not existing: ``-resource_properties.my_property : ""`` + compare_duration (Union[dict, ~google.cloud.securitycenter_v1.types.Duration]): When compare_duration is set, the GroupResult's "state_change" + property is updated to indicate whether the asset was added, removed, or + remained present during the compare_duration period of time that + precedes the read_time. This is the time between (read_time - + compare_duration) and read_time. + + The state change value is derived based on the presence of the asset at + the two points in time. Intermediate state changes between the two times + don't affect the result. For example, the results aren't affected if the + asset is removed and re-created again. + + Possible "state_change" values when compare_duration is specified: + + - "ADDED": indicates that the asset was not present at the start of + compare_duration, but present at reference_time. + - "REMOVED": indicates that the asset was present at the start of + compare_duration, but not present at reference_time. + - "ACTIVE": indicates that the asset was present at both the start and + the end of the time period defined by compare_duration and + reference_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set for all + assets present at read_time. + + If this field is set then ``state_change`` must be a specified field in + ``group_by``. + + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.securitycenter_v1.types.Duration` + read_time (Union[dict, ~google.cloud.securitycenter_v1.types.Timestamp]): Time used as a reference point when filtering assets. The filter is limited + to assets existing at the supplied time and their values are those at that + specific time. Absence of this field will default to the API's version of + NOW. + + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.securitycenter_v1.types.Timestamp` + page_size (int): The maximum number of resources contained in the + underlying API response. If page streaming is performed per- + resource, this parameter does not affect the return value. If page + streaming is performed per-page, this determines the maximum number + of resources in a page. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -1285,7 +1088,10 @@ def get_notification_config( that is provided to the method. Returns: - A :class:`~google.cloud.securitycenter_v1.types.NotificationConfig` instance. + A :class:`~google.api_core.page_iterator.PageIterator` instance. + An iterable of :class:`~google.cloud.securitycenter_v1.types.GroupResult` instances. + You can also iterate over the pages of the response + using its `pages` property. Raises: google.api_core.exceptions.GoogleAPICallError: If the request @@ -1295,22 +1101,29 @@ def get_notification_config( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "get_notification_config" not in self._inner_api_calls: + if "group_assets" not in self._inner_api_calls: self._inner_api_calls[ - "get_notification_config" + "group_assets" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_notification_config, - default_retry=self._method_configs["GetNotificationConfig"].retry, - default_timeout=self._method_configs["GetNotificationConfig"].timeout, + self.transport.group_assets, + default_retry=self._method_configs["GroupAssets"].retry, + default_timeout=self._method_configs["GroupAssets"].timeout, client_info=self._client_info, ) - request = securitycenter_service_pb2.GetNotificationConfigRequest(name=name,) + request = securitycenter_service_pb2.GroupAssetsRequest( + parent=parent, + group_by=group_by, + filter=filter_, + compare_duration=compare_duration, + read_time=read_time, + page_size=page_size, + ) if metadata is None: metadata = [] metadata = list(metadata) try: - routing_header = [("name", name)] + routing_header = [("parent", parent)] except AttributeError: pass else: @@ -1319,102 +1132,187 @@ def get_notification_config( ) metadata.append(routing_metadata) - return self._inner_api_calls["get_notification_config"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) + iterator = google.api_core.page_iterator.GRPCIterator( + client=None, + method=functools.partial( + self._inner_api_calls["group_assets"], + retry=retry, + timeout=timeout, + metadata=metadata, + ), + request=request, + items_field="group_by_results", + request_token_field="page_token", + response_token_field="next_page_token", + ) + return iterator + + def group_findings( + self, + parent, + group_by, + filter_=None, + read_time=None, + compare_duration=None, + page_size=None, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT, + metadata=None, + ): + """ + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. Example: + /v1/organizations/{organization_id}/sources/-/findings + + Example: + >>> from google.cloud import securitycenter_v1 + >>> + >>> client = securitycenter_v1.SecurityCenterClient() + >>> + >>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]') + >>> + >>> # TODO: Initialize `group_by`: + >>> group_by = '' + >>> + >>> # Iterate over all results + >>> for element in client.group_findings(parent, group_by): + ... # process element + ... pass + >>> + >>> + >>> # Alternatively: + >>> + >>> # Iterate over results one page at a time + >>> for page in client.group_findings(parent, group_by).pages: + ... for element in page: + ... # process element + ... pass + + Args: + parent (str): Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]". To groupBy across + all sources provide a source_id of ``-``. For example: + organizations/{organization_id}/sources/- + group_by (str): Required. Expression that defines what assets fields to use for + grouping (including ``state_change``). The string value should follow + SQL syntax: comma separated list of fields. For example: + "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + + The following fields are supported when compare_duration is set: + + - state_change + filter_ (str): Expression that defines the filter to apply across findings. The + expression is a list of one or more restrictions combined via logical + operators ``AND`` and ``OR``. Parentheses are supported, and ``OR`` has + higher precedence than ``AND``. + + Restrictions have the form `` `` and may have a + ``-`` character in front of them to indicate negation. Examples include: + + - name + - source_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - parent: ``=``, ``:`` + + - resource_name: ``=``, ``:`` + + - state: ``=``, ``:`` + + - category: ``=``, ``:`` + + - external_uri: ``=``, ``:`` + + - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an RFC3339 string. + Examples: ``event_time = "2019-06-10T16:07:18-07:00"`` + ``event_time = 1560208038000`` + + - security_marks.marks: ``=``, ``:`` + + - source_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, ``<=`` - def get_organization_settings( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets the settings for an organization. + For example, ``source_properties.size = 100`` is a valid filter string. - Example: - >>> from google.cloud import securitycenter_v1 - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> name = client.organization_settings_path('[ORGANIZATION]') - >>> - >>> response = client.get_organization_settings(name) + Use a partial match on the empty string to filter based on a property + existing: ``source_properties.my_property : ""`` - Args: - name (str): Required. Name of the organization to get organization settings for. - Its format is "organizations/[organization_id]/organizationSettings". - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. + Use a negated partial match on the empty string to filter based on a + property not existing: ``-source_properties.my_property : ""`` + read_time (Union[dict, ~google.cloud.securitycenter_v1.types.Timestamp]): Time used as a reference point when filtering findings. The filter is + limited to findings existing at the supplied time and their values are + those at that specific time. Absence of this field will default to the + API's version of NOW. - Returns: - A :class:`~google.cloud.securitycenter_v1.types.OrganizationSettings` instance. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.securitycenter_v1.types.Timestamp` + compare_duration (Union[dict, ~google.cloud.securitycenter_v1.types.Duration]): When compare_duration is set, the GroupResult's "state_change" + attribute is updated to indicate whether the finding had its state + changed, the finding's state remained unchanged, or if the finding was + added during the compare_duration period of time that precedes the + read_time. This is the time between (read_time - compare_duration) and + read_time. - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_organization_settings" not in self._inner_api_calls: - self._inner_api_calls[ - "get_organization_settings" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_organization_settings, - default_retry=self._method_configs["GetOrganizationSettings"].retry, - default_timeout=self._method_configs["GetOrganizationSettings"].timeout, - client_info=self._client_info, - ) + The state_change value is derived based on the presence and state of the + finding at the two points in time. Intermediate state changes between + the two times don't affect the result. For example, the results aren't + affected if the finding is made inactive and then active again. - request = securitycenter_service_pb2.GetOrganizationSettingsRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) + Possible "state_change" values when compare_duration is specified: - return self._inner_api_calls["get_organization_settings"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) + - "CHANGED": indicates that the finding was present and matched the + given filter at the start of compare_duration, but changed its state + at read_time. + - "UNCHANGED": indicates that the finding was present and matched the + given filter at the start of compare_duration and did not change + state at read_time. + - "ADDED": indicates that the finding did not match the given filter or + was not present at the start of compare_duration, but was present at + read_time. + - "REMOVED": indicates that the finding was present and matched the + filter at the start of compare_duration, but did not match the filter + at read_time. - def get_source( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets a source. + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set for all + findings present at read_time. - Example: - >>> from google.cloud import securitycenter_v1 - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> name = client.source_path('[ORGANIZATION]', '[SOURCE]') - >>> - >>> response = client.get_source(name) + If this field is set then ``state_change`` must be a specified field in + ``group_by``. - Args: - name (str): Required. Relative resource name of the source. Its format is - "organizations/[organization_id]/source/[source_id]". + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.securitycenter_v1.types.Duration` + page_size (int): The maximum number of resources contained in the + underlying API response. If page streaming is performed per- + resource, this parameter does not affect the return value. If page + streaming is performed per-page, this determines the maximum number + of resources in a page. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -1425,7 +1323,10 @@ def get_source( that is provided to the method. Returns: - A :class:`~google.cloud.securitycenter_v1.types.Source` instance. + A :class:`~google.api_core.page_iterator.PageIterator` instance. + An iterable of :class:`~google.cloud.securitycenter_v1.types.GroupResult` instances. + You can also iterate over the pages of the response + using its `pages` property. Raises: google.api_core.exceptions.GoogleAPICallError: If the request @@ -1435,22 +1336,29 @@ def get_source( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "get_source" not in self._inner_api_calls: + if "group_findings" not in self._inner_api_calls: self._inner_api_calls[ - "get_source" + "group_findings" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_source, - default_retry=self._method_configs["GetSource"].retry, - default_timeout=self._method_configs["GetSource"].timeout, + self.transport.group_findings, + default_retry=self._method_configs["GroupFindings"].retry, + default_timeout=self._method_configs["GroupFindings"].timeout, client_info=self._client_info, ) - request = securitycenter_service_pb2.GetSourceRequest(name=name,) + request = securitycenter_service_pb2.GroupFindingsRequest( + parent=parent, + group_by=group_by, + filter=filter_, + read_time=read_time, + compare_duration=compare_duration, + page_size=page_size, + ) if metadata is None: metadata = [] metadata = list(metadata) try: - routing_header = [("name", name)] + routing_header = [("parent", parent)] except AttributeError: pass else: @@ -1459,9 +1367,20 @@ def get_source( ) metadata.append(routing_metadata) - return self._inner_api_calls["get_source"]( - request, retry=retry, timeout=timeout, metadata=metadata + iterator = google.api_core.page_iterator.GRPCIterator( + client=None, + method=functools.partial( + self._inner_api_calls["group_findings"], + retry=retry, + timeout=timeout, + metadata=metadata, + ), + request=request, + items_field="group_by_results", + request_token_field="page_token", + response_token_field="next_page_token", ) + return iterator def list_assets( self, @@ -2394,6 +2313,87 @@ def set_iam_policy( request, retry=retry, timeout=timeout, metadata=metadata ) + def test_iam_permissions( + self, + resource, + permissions, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT, + metadata=None, + ): + """ + Returns the permissions that a caller has on the specified source. + + Example: + >>> from google.cloud import securitycenter_v1 + >>> + >>> client = securitycenter_v1.SecurityCenterClient() + >>> + >>> # TODO: Initialize `resource`: + >>> resource = '' + >>> + >>> # TODO: Initialize `permissions`: + >>> permissions = [] + >>> + >>> response = client.test_iam_permissions(resource, permissions) + + Args: + resource (str): REQUIRED: The resource for which the policy detail is being requested. + See the operation documentation for the appropriate value for this field. + permissions (list[str]): The set of permissions to check for the ``resource``. Permissions + with wildcards (such as '*' or 'storage.*') are not allowed. For more + information see `IAM + Overview `__. + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will + be retried using a default configuration. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata + that is provided to the method. + + Returns: + A :class:`~google.cloud.securitycenter_v1.types.TestIamPermissionsResponse` instance. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + # Wrap the transport method to add retry and timeout logic. + if "test_iam_permissions" not in self._inner_api_calls: + self._inner_api_calls[ + "test_iam_permissions" + ] = google.api_core.gapic_v1.method.wrap_method( + self.transport.test_iam_permissions, + default_retry=self._method_configs["TestIamPermissions"].retry, + default_timeout=self._method_configs["TestIamPermissions"].timeout, + client_info=self._client_info, + ) + + request = iam_policy_pb2.TestIamPermissionsRequest( + resource=resource, permissions=permissions, + ) + if metadata is None: + metadata = [] + metadata = list(metadata) + try: + routing_header = [("resource", resource)] + except AttributeError: + pass + else: + routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( + routing_header + ) + metadata.append(routing_metadata) + + return self._inner_api_calls["test_iam_permissions"]( + request, retry=retry, timeout=timeout, metadata=metadata + ) + def update_finding( self, finding, diff --git a/google/cloud/securitycenter_v1/gapic/security_center_client_config.py b/google/cloud/securitycenter_v1/gapic/security_center_client_config.py index 7bf5a897..111431ea 100644 --- a/google/cloud/securitycenter_v1/gapic/security_center_client_config.py +++ b/google/cloud/securitycenter_v1/gapic/security_center_client_config.py @@ -2,135 +2,174 @@ "interfaces": { "google.cloud.securitycenter.v1.SecurityCenter": { "retry_codes": { - "idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "non_idempotent": [], + "retry_policy_1_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], + "no_retry_2_codes": [], + "no_retry_codes": [], + "retry_policy_2_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], + "no_retry_1_codes": [], }, "retry_params": { - "default": { + "retry_policy_1_params": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 60000, + }, + "retry_policy_2_params": { "initial_retry_delay_millis": 100, "retry_delay_multiplier": 1.3, "max_retry_delay_millis": 60000, "initial_rpc_timeout_millis": 480000, "rpc_timeout_multiplier": 1.0, "max_rpc_timeout_millis": 480000, - "total_timeout_millis": 600000, - } - }, - "methods": { - "GetIamPolicy": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "total_timeout_millis": 480000, }, - "GroupAssets": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", - }, - "GroupFindings": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "no_retry_params": { + "initial_retry_delay_millis": 0, + "retry_delay_multiplier": 0.0, + "max_retry_delay_millis": 0, + "initial_rpc_timeout_millis": 0, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 0, + "total_timeout_millis": 0, + }, + "no_retry_1_params": { + "initial_retry_delay_millis": 0, + "retry_delay_multiplier": 0.0, + "max_retry_delay_millis": 0, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 60000, }, - "TestIamPermissions": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "no_retry_2_params": { + "initial_retry_delay_millis": 0, + "retry_delay_multiplier": 0.0, + "max_retry_delay_millis": 0, + "initial_rpc_timeout_millis": 480000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 480000, + "total_timeout_millis": 480000, }, + }, + "methods": { "CreateSource": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "CreateFinding": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "CreateNotificationConfig": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "DeleteNotificationConfig": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", + }, + "GetIamPolicy": { + "timeout_millis": 60000, + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "GetNotificationConfig": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "GetOrganizationSettings": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "GetSource": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", + }, + "GroupAssets": { + "timeout_millis": 480000, + "retry_codes_name": "retry_policy_2_codes", + "retry_params_name": "retry_policy_2_params", + }, + "GroupFindings": { + "timeout_millis": 480000, + "retry_codes_name": "retry_policy_2_codes", + "retry_params_name": "retry_policy_2_params", }, "ListAssets": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "timeout_millis": 480000, + "retry_codes_name": "retry_policy_2_codes", + "retry_params_name": "retry_policy_2_params", }, "ListFindings": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "timeout_millis": 480000, + "retry_codes_name": "retry_policy_2_codes", + "retry_params_name": "retry_policy_2_params", }, "ListNotificationConfigs": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "ListSources": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "RunAssetDiscovery": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "SetFindingState": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "SetIamPolicy": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", + }, + "TestIamPermissions": { + "timeout_millis": 60000, + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "UpdateFinding": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "UpdateNotificationConfig": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "UpdateOrganizationSettings": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "UpdateSource": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "UpdateSecurityMarks": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "timeout_millis": 480000, + "retry_codes_name": "no_retry_2_codes", + "retry_params_name": "no_retry_2_params", }, }, } diff --git a/google/cloud/securitycenter_v1/gapic/transports/security_center_grpc_transport.py b/google/cloud/securitycenter_v1/gapic/transports/security_center_grpc_transport.py index 1d16b3f2..58249a17 100644 --- a/google/cloud/securitycenter_v1/gapic/transports/security_center_grpc_transport.py +++ b/google/cloud/securitycenter_v1/gapic/transports/security_center_grpc_transport.py @@ -120,63 +120,6 @@ def channel(self): """ return self._channel - @property - def get_iam_policy(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.get_iam_policy`. - - Gets the access control policy on the specified Source. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].GetIamPolicy - - @property - def group_assets(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.group_assets`. - - Filters an organization's assets and groups them by their specified - properties. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].GroupAssets - - @property - def group_findings(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.group_findings`. - - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. Example: - /v1/organizations/{organization_id}/sources/-/findings - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].GroupFindings - - @property - def test_iam_permissions(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.test_iam_permissions`. - - Returns the permissions that a caller has on the specified source. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].TestIamPermissions - @property def create_source(self): """Return the gRPC stub for :meth:`SecurityCenterClient.create_source`. @@ -230,6 +173,19 @@ def delete_notification_config(self): """ return self._stubs["security_center_stub"].DeleteNotificationConfig + @property + def get_iam_policy(self): + """Return the gRPC stub for :meth:`SecurityCenterClient.get_iam_policy`. + + Gets the access control policy on the specified Source. + + Returns: + Callable: A callable which accepts the appropriate + deserialized request object and returns a + deserialized response object. + """ + return self._stubs["security_center_stub"].GetIamPolicy + @property def get_notification_config(self): """Return the gRPC stub for :meth:`SecurityCenterClient.get_notification_config`. @@ -269,6 +225,37 @@ def get_source(self): """ return self._stubs["security_center_stub"].GetSource + @property + def group_assets(self): + """Return the gRPC stub for :meth:`SecurityCenterClient.group_assets`. + + Filters an organization's assets and groups them by their specified + properties. + + Returns: + Callable: A callable which accepts the appropriate + deserialized request object and returns a + deserialized response object. + """ + return self._stubs["security_center_stub"].GroupAssets + + @property + def group_findings(self): + """Return the gRPC stub for :meth:`SecurityCenterClient.group_findings`. + + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. Example: + /v1/organizations/{organization_id}/sources/-/findings + + Returns: + Callable: A callable which accepts the appropriate + deserialized request object and returns a + deserialized response object. + """ + return self._stubs["security_center_stub"].GroupFindings + @property def list_assets(self): """Return the gRPC stub for :meth:`SecurityCenterClient.list_assets`. @@ -368,6 +355,19 @@ def set_iam_policy(self): """ return self._stubs["security_center_stub"].SetIamPolicy + @property + def test_iam_permissions(self): + """Return the gRPC stub for :meth:`SecurityCenterClient.test_iam_permissions`. + + Returns the permissions that a caller has on the specified source. + + Returns: + Callable: A callable which accepts the appropriate + deserialized request object and returns a + deserialized response object. + """ + return self._stubs["security_center_stub"].TestIamPermissions + @property def update_finding(self): """Return the gRPC stub for :meth:`SecurityCenterClient.update_finding`. diff --git a/synth.metadata b/synth.metadata index bf3edc49..23f3e9f8 100644 --- a/synth.metadata +++ b/synth.metadata @@ -11,8 +11,8 @@ "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "afa7f44f57e6ac33cf060d1764c9940dd404f725", - "internalRef": "321179822" + "sha": "9362f58401cfe3b463b75a18d134bb818ad4dcb2", + "internalRef": "321179885" } }, { diff --git a/tests/unit/gapic/v1/test_security_center_client_v1.py b/tests/unit/gapic/v1/test_security_center_client_v1.py index dbecf0c9..96cf1bd2 100644 --- a/tests/unit/gapic/v1/test_security_center_client_v1.py +++ b/tests/unit/gapic/v1/test_security_center_client_v1.py @@ -74,196 +74,6 @@ class CustomException(Exception): class TestSecurityCenterClient(object): - def test_get_iam_policy(self): - # Setup Expected Response - version = 351608024 - etag = b"21" - expected_response = {"version": version, "etag": etag} - expected_response = policy_pb2.Policy(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - resource = "resource-341064690" - - response = client.get_iam_policy(resource) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_iam_policy_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - resource = "resource-341064690" - - with pytest.raises(CustomException): - client.get_iam_policy(resource) - - def test_group_assets(self): - # Setup Expected Response - next_page_token = "" - total_size = 705419236 - group_by_results_element = {} - group_by_results = [group_by_results_element] - expected_response = { - "next_page_token": next_page_token, - "total_size": total_size, - "group_by_results": group_by_results, - } - expected_response = securitycenter_service_pb2.GroupAssetsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - parent = client.organization_path("[ORGANIZATION]") - group_by = "groupBy506361367" - - paged_list_response = client.group_assets(parent, group_by) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.group_by_results[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.GroupAssetsRequest( - parent=parent, group_by=group_by - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_group_assets_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - parent = client.organization_path("[ORGANIZATION]") - group_by = "groupBy506361367" - - paged_list_response = client.group_assets(parent, group_by) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_group_findings(self): - # Setup Expected Response - next_page_token = "" - total_size = 705419236 - group_by_results_element = {} - group_by_results = [group_by_results_element] - expected_response = { - "next_page_token": next_page_token, - "total_size": total_size, - "group_by_results": group_by_results, - } - expected_response = securitycenter_service_pb2.GroupFindingsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - parent = client.source_path("[ORGANIZATION]", "[SOURCE]") - group_by = "groupBy506361367" - - paged_list_response = client.group_findings(parent, group_by) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.group_by_results[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.GroupFindingsRequest( - parent=parent, group_by=group_by - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_group_findings_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - parent = client.source_path("[ORGANIZATION]", "[SOURCE]") - group_by = "groupBy506361367" - - paged_list_response = client.group_findings(parent, group_by) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_test_iam_permissions(self): - # Setup Expected Response - expected_response = {} - expected_response = iam_policy_pb2.TestIamPermissionsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - resource = "resource-341064690" - permissions = [] - - response = client.test_iam_permissions(resource, permissions) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = iam_policy_pb2.TestIamPermissionsRequest( - resource=resource, permissions=permissions - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_test_iam_permissions_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - resource = "resource-341064690" - permissions = [] - - with pytest.raises(CustomException): - client.test_iam_permissions(resource, permissions) - def test_create_source(self): # Setup Expected Response name = "name3373707" @@ -459,6 +269,45 @@ def test_delete_notification_config_exception(self): with pytest.raises(CustomException): client.delete_notification_config(name) + def test_get_iam_policy(self): + # Setup Expected Response + version = 351608024 + etag = b"21" + expected_response = {"version": version, "etag": etag} + expected_response = policy_pb2.Policy(**expected_response) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + patch = mock.patch("google.api_core.grpc_helpers.create_channel") + with patch as create_channel: + create_channel.return_value = channel + client = securitycenter_v1.SecurityCenterClient() + + # Setup Request + resource = "resource-341064690" + + response = client.get_iam_policy(resource) + assert expected_response == response + + assert len(channel.requests) == 1 + expected_request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_get_iam_policy_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + patch = mock.patch("google.api_core.grpc_helpers.create_channel") + with patch as create_channel: + create_channel.return_value = channel + client = securitycenter_v1.SecurityCenterClient() + + # Setup request + resource = "resource-341064690" + + with pytest.raises(CustomException): + client.get_iam_policy(resource) + def test_get_notification_config(self): # Setup Expected Response name_2 = "name2-1052831874" @@ -603,6 +452,114 @@ def test_get_source_exception(self): with pytest.raises(CustomException): client.get_source(name) + def test_group_assets(self): + # Setup Expected Response + next_page_token = "" + total_size = 705419236 + group_by_results_element = {} + group_by_results = [group_by_results_element] + expected_response = { + "next_page_token": next_page_token, + "total_size": total_size, + "group_by_results": group_by_results, + } + expected_response = securitycenter_service_pb2.GroupAssetsResponse( + **expected_response + ) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + patch = mock.patch("google.api_core.grpc_helpers.create_channel") + with patch as create_channel: + create_channel.return_value = channel + client = securitycenter_v1.SecurityCenterClient() + + # Setup Request + parent = client.organization_path("[ORGANIZATION]") + group_by = "groupBy506361367" + + paged_list_response = client.group_assets(parent, group_by) + resources = list(paged_list_response) + assert len(resources) == 1 + + assert expected_response.group_by_results[0] == resources[0] + + assert len(channel.requests) == 1 + expected_request = securitycenter_service_pb2.GroupAssetsRequest( + parent=parent, group_by=group_by + ) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_group_assets_exception(self): + channel = ChannelStub(responses=[CustomException()]) + patch = mock.patch("google.api_core.grpc_helpers.create_channel") + with patch as create_channel: + create_channel.return_value = channel + client = securitycenter_v1.SecurityCenterClient() + + # Setup request + parent = client.organization_path("[ORGANIZATION]") + group_by = "groupBy506361367" + + paged_list_response = client.group_assets(parent, group_by) + with pytest.raises(CustomException): + list(paged_list_response) + + def test_group_findings(self): + # Setup Expected Response + next_page_token = "" + total_size = 705419236 + group_by_results_element = {} + group_by_results = [group_by_results_element] + expected_response = { + "next_page_token": next_page_token, + "total_size": total_size, + "group_by_results": group_by_results, + } + expected_response = securitycenter_service_pb2.GroupFindingsResponse( + **expected_response + ) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + patch = mock.patch("google.api_core.grpc_helpers.create_channel") + with patch as create_channel: + create_channel.return_value = channel + client = securitycenter_v1.SecurityCenterClient() + + # Setup Request + parent = client.source_path("[ORGANIZATION]", "[SOURCE]") + group_by = "groupBy506361367" + + paged_list_response = client.group_findings(parent, group_by) + resources = list(paged_list_response) + assert len(resources) == 1 + + assert expected_response.group_by_results[0] == resources[0] + + assert len(channel.requests) == 1 + expected_request = securitycenter_service_pb2.GroupFindingsRequest( + parent=parent, group_by=group_by + ) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_group_findings_exception(self): + channel = ChannelStub(responses=[CustomException()]) + patch = mock.patch("google.api_core.grpc_helpers.create_channel") + with patch as create_channel: + create_channel.return_value = channel + client = securitycenter_v1.SecurityCenterClient() + + # Setup request + parent = client.source_path("[ORGANIZATION]", "[SOURCE]") + group_by = "groupBy506361367" + + paged_list_response = client.group_findings(parent, group_by) + with pytest.raises(CustomException): + list(paged_list_response) + def test_list_assets(self): # Setup Expected Response next_page_token = "" @@ -949,6 +906,49 @@ def test_set_iam_policy_exception(self): with pytest.raises(CustomException): client.set_iam_policy(resource, policy) + def test_test_iam_permissions(self): + # Setup Expected Response + expected_response = {} + expected_response = iam_policy_pb2.TestIamPermissionsResponse( + **expected_response + ) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + patch = mock.patch("google.api_core.grpc_helpers.create_channel") + with patch as create_channel: + create_channel.return_value = channel + client = securitycenter_v1.SecurityCenterClient() + + # Setup Request + resource = "resource-341064690" + permissions = [] + + response = client.test_iam_permissions(resource, permissions) + assert expected_response == response + + assert len(channel.requests) == 1 + expected_request = iam_policy_pb2.TestIamPermissionsRequest( + resource=resource, permissions=permissions + ) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_test_iam_permissions_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + patch = mock.patch("google.api_core.grpc_helpers.create_channel") + with patch as create_channel: + create_channel.return_value = channel + client = securitycenter_v1.SecurityCenterClient() + + # Setup request + resource = "resource-341064690" + permissions = [] + + with pytest.raises(CustomException): + client.test_iam_permissions(resource, permissions) + def test_update_finding(self): # Setup Expected Response name = "name3373707" From 7fafe6737b8d16c69756fd2af41ba8c5f4198b22 Mon Sep 17 00:00:00 2001 From: yoshi-automation Date: Sat, 1 Aug 2020 11:20:41 -0700 Subject: [PATCH 04/17] fix: add resource config to scc/v1beta1/Asset chore: update various comments PiperOrigin-RevId: 322867095 Source-Author: Google APIs Source-Date: Thu Jul 23 14:30:13 2020 -0700 Source-Repo: googleapis/googleapis Source-Sha: e26e1839a45445d13cd45b1be3b1523defb72fee Source-Link: https://github.com/googleapis/googleapis/commit/e26e1839a45445d13cd45b1be3b1523defb72fee --- docs/gapic/v1beta1/api.rst | 4 +- docs/gapic/v1beta1/types.rst | 4 +- .../securitycenter_v1beta1/proto/asset.proto | 44 +++++++------ .../securitycenter_v1beta1/proto/asset_pb2.py | 64 ++++++++++--------- .../proto/finding.proto | 29 ++++----- .../proto/finding_pb2.py | 23 +++---- .../proto/organization_settings.proto | 7 +- .../proto/organization_settings_pb2.py | 4 +- .../proto/run_asset_discovery_response.proto | 3 +- .../proto/security_marks.proto | 9 ++- .../proto/security_marks_pb2.py | 8 +-- .../proto/securitycenter_service.proto | 3 +- .../securitycenter_v1beta1/proto/source.proto | 7 +- .../proto/source_pb2.py | 10 +-- synth.metadata | 4 +- 15 files changed, 115 insertions(+), 108 deletions(-) diff --git a/docs/gapic/v1beta1/api.rst b/docs/gapic/v1beta1/api.rst index 5bf656fe..89fdb487 100644 --- a/docs/gapic/v1beta1/api.rst +++ b/docs/gapic/v1beta1/api.rst @@ -1,5 +1,5 @@ -Client for Cloud Security Command Center API -============================================ +Client for Security Command Center API +====================================== .. automodule:: google.cloud.securitycenter_v1beta1 :members: diff --git a/docs/gapic/v1beta1/types.rst b/docs/gapic/v1beta1/types.rst index 4af19d8c..1ec286a2 100644 --- a/docs/gapic/v1beta1/types.rst +++ b/docs/gapic/v1beta1/types.rst @@ -1,5 +1,5 @@ -Types for Cloud Security Command Center API Client -================================================== +Types for Security Command Center API Client +============================================ .. automodule:: google.cloud.securitycenter_v1beta1.types :members: \ No newline at end of file diff --git a/google/cloud/securitycenter_v1beta1/proto/asset.proto b/google/cloud/securitycenter_v1beta1/proto/asset.proto index 85d0e090..b73f7d5b 100644 --- a/google/cloud/securitycenter_v1beta1/proto/asset.proto +++ b/google/cloud/securitycenter_v1beta1/proto/asset.proto @@ -1,4 +1,4 @@ -// Copyright 2019 Google LLC. +// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -11,13 +11,13 @@ // 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. -// syntax = "proto3"; package google.cloud.securitycenter.v1beta1; import "google/api/field_behavior.proto"; +import "google/api/resource.proto"; import "google/cloud/securitycenter/v1beta1/security_marks.proto"; import "google/protobuf/struct.proto"; import "google/protobuf/timestamp.proto"; @@ -27,25 +27,31 @@ option go_package = "google.golang.org/genproto/googleapis/cloud/securitycenter/ option java_multiple_files = true; option java_package = "com.google.cloud.securitycenter.v1beta1"; -// Cloud Security Command Center's (Cloud SCC) representation of a Google Cloud -// Platform (GCP) resource. +// Security Command Center representation of a Google Cloud +// resource. // -// The Asset is a Cloud SCC resource that captures information about a single -// GCP resource. All modifications to an Asset are only within the context of -// Cloud SCC and don't affect the referenced GCP resource. +// The Asset is a Security Command Center resource that captures information +// about a single Google Cloud resource. All modifications to an Asset are only +// within the context of Security Command Center and don't affect the referenced +// Google Cloud resource. message Asset { - // Cloud SCC managed properties. These properties are managed by Cloud SCC and - // cannot be modified by the user. + option (google.api.resource) = { + type: "securitycenter.googleapis.com/Asset" + pattern: "organizations/{organization}/assets/{asset}" + }; + + // Security Command Center managed properties. These properties are managed by + // Security Command Center and cannot be modified by the user. message SecurityCenterProperties { - // Immutable. The full resource name of the GCP resource this asset + // Immutable. The full resource name of the Google Cloud resource this asset // represents. This field is immutable after create time. See: // https://cloud.google.com/apis/design/resource_names#full_resource_name string resource_name = 1 [(google.api.field_behavior) = IMMUTABLE]; - // The type of the GCP resource. Examples include: APPLICATION, + // The type of the Google Cloud resource. Examples include: APPLICATION, // PROJECT, and ORGANIZATION. This is a case insensitive field defined by - // Cloud SCC and/or the producer of the resource and is immutable - // after create time. + // Security Command Center and/or the producer of the resource and is + // immutable after create time. string resource_type = 2; // The full resource name of the immediate parent of the resource. See: @@ -66,22 +72,22 @@ message Asset { // "organizations/{organization_id}/assets/{asset_id}". string name = 1; - // Cloud SCC managed properties. These properties are managed by - // Cloud SCC and cannot be modified by the user. + // Security Command Center managed properties. These properties are managed by + // Security Command Center and cannot be modified by the user. SecurityCenterProperties security_center_properties = 2; // Resource managed properties. These properties are managed and defined by - // the GCP resource and cannot be modified by the user. + // the Google Cloud resource and cannot be modified by the user. map resource_properties = 7; // User specified security marks. These marks are entirely managed by the user // and come from the SecurityMarks resource that belongs to the asset. SecurityMarks security_marks = 8; - // The time at which the asset was created in Cloud SCC. + // The time at which the asset was created in Security Command Center. google.protobuf.Timestamp create_time = 9; - // The time at which the asset was last updated, added, or deleted in Cloud - // SCC. + // The time at which the asset was last updated, added, or deleted in Security + // Command Center. google.protobuf.Timestamp update_time = 10; } diff --git a/google/cloud/securitycenter_v1beta1/proto/asset_pb2.py b/google/cloud/securitycenter_v1beta1/proto/asset_pb2.py index e1e488ee..cf7ceb98 100644 --- a/google/cloud/securitycenter_v1beta1/proto/asset_pb2.py +++ b/google/cloud/securitycenter_v1beta1/proto/asset_pb2.py @@ -13,6 +13,7 @@ from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 +from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 from google.cloud.securitycenter_v1beta1.proto import ( security_marks_pb2 as google_dot_cloud_dot_securitycenter__v1beta1_dot_proto_dot_security__marks__pb2, ) @@ -27,9 +28,10 @@ syntax="proto3", serialized_options=b"\n'com.google.cloud.securitycenter.v1beta1P\001ZQgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1;securitycenter", create_key=_descriptor._internal_create_key, - serialized_pb=b"\n5google/cloud/securitycenter_v1beta1/proto/asset.proto\x12#google.cloud.securitycenter.v1beta1\x1a\x1fgoogle/api/field_behavior.proto\x1a>google/cloud/securitycenter_v1beta1/proto/security_marks.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1cgoogle/api/annotations.proto\"\xfc\x04\n\x05\x41sset\x12\x0c\n\x04name\x18\x01 \x01(\t\x12g\n\x1asecurity_center_properties\x18\x02 \x01(\x0b\x32\x43.google.cloud.securitycenter.v1beta1.Asset.SecurityCenterProperties\x12_\n\x13resource_properties\x18\x07 \x03(\x0b\x32\x42.google.cloud.securitycenter.v1beta1.Asset.ResourcePropertiesEntry\x12J\n\x0esecurity_marks\x18\x08 \x01(\x0b\x32\x32.google.cloud.securitycenter.v1beta1.SecurityMarks\x12/\n\x0b\x63reate_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0bupdate_time\x18\n \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x1a\x99\x01\n\x18SecurityCenterProperties\x12\x1a\n\rresource_name\x18\x01 \x01(\tB\x03\xe0\x41\x05\x12\x15\n\rresource_type\x18\x02 \x01(\t\x12\x17\n\x0fresource_parent\x18\x03 \x01(\t\x12\x18\n\x10resource_project\x18\x04 \x01(\t\x12\x17\n\x0fresource_owners\x18\x05 \x03(\t\x1aQ\n\x17ResourcePropertiesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12%\n\x05value\x18\x02 \x01(\x0b\x32\x16.google.protobuf.Value:\x02\x38\x01\x42~\n'com.google.cloud.securitycenter.v1beta1P\x01ZQgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1;securitycenterb\x06proto3", + serialized_pb=b"\n5google/cloud/securitycenter_v1beta1/proto/asset.proto\x12#google.cloud.securitycenter.v1beta1\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a>google/cloud/securitycenter_v1beta1/proto/security_marks.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1cgoogle/api/annotations.proto\"\xd3\x05\n\x05\x41sset\x12\x0c\n\x04name\x18\x01 \x01(\t\x12g\n\x1asecurity_center_properties\x18\x02 \x01(\x0b\x32\x43.google.cloud.securitycenter.v1beta1.Asset.SecurityCenterProperties\x12_\n\x13resource_properties\x18\x07 \x03(\x0b\x32\x42.google.cloud.securitycenter.v1beta1.Asset.ResourcePropertiesEntry\x12J\n\x0esecurity_marks\x18\x08 \x01(\x0b\x32\x32.google.cloud.securitycenter.v1beta1.SecurityMarks\x12/\n\x0b\x63reate_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0bupdate_time\x18\n \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x1a\x99\x01\n\x18SecurityCenterProperties\x12\x1a\n\rresource_name\x18\x01 \x01(\tB\x03\xe0\x41\x05\x12\x15\n\rresource_type\x18\x02 \x01(\t\x12\x17\n\x0fresource_parent\x18\x03 \x01(\t\x12\x18\n\x10resource_project\x18\x04 \x01(\t\x12\x17\n\x0fresource_owners\x18\x05 \x03(\t\x1aQ\n\x17ResourcePropertiesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12%\n\x05value\x18\x02 \x01(\x0b\x32\x16.google.protobuf.Value:\x02\x38\x01:U\xea\x41R\n#securitycenter.googleapis.com/Asset\x12+organizations/{organization}/assets/{asset}B~\n'com.google.cloud.securitycenter.v1beta1P\x01ZQgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1;securitycenterb\x06proto3", dependencies=[ google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, + google_dot_api_dot_resource__pb2.DESCRIPTOR, google_dot_cloud_dot_securitycenter__v1beta1_dot_proto_dot_security__marks__pb2.DESCRIPTOR, google_dot_protobuf_dot_struct__pb2.DESCRIPTOR, google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, @@ -150,8 +152,8 @@ syntax="proto3", extension_ranges=[], oneofs=[], - serialized_start=685, - serialized_end=838, + serialized_start=712, + serialized_end=865, ) _ASSET_RESOURCEPROPERTIESENTRY = _descriptor.Descriptor( @@ -209,8 +211,8 @@ syntax="proto3", extension_ranges=[], oneofs=[], - serialized_start=840, - serialized_end=921, + serialized_start=867, + serialized_end=948, ) _ASSET = _descriptor.Descriptor( @@ -339,13 +341,13 @@ extensions=[], nested_types=[_ASSET_SECURITYCENTERPROPERTIES, _ASSET_RESOURCEPROPERTIESENTRY,], enum_types=[], - serialized_options=None, + serialized_options=b"\352AR\n#securitycenter.googleapis.com/Asset\022+organizations/{organization}/assets/{asset}", is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], - serialized_start=285, - serialized_end=921, + serialized_start=312, + serialized_end=1035, ) _ASSET_SECURITYCENTERPROPERTIES.containing_type = _ASSET @@ -383,20 +385,21 @@ { "DESCRIPTOR": _ASSET_SECURITYCENTERPROPERTIES, "__module__": "google.cloud.securitycenter_v1beta1.proto.asset_pb2", - "__doc__": """Cloud SCC managed properties. These properties are managed by Cloud - SCC and cannot be modified by the user. + "__doc__": """Security Command Center managed properties. These properties are + managed by Security Command Center and cannot be modified by the user. Attributes: resource_name: - Immutable. The full resource name of the GCP resource this - asset represents. This field is immutable after create time. - See: https://cloud.google.com/apis/design/resource_names#full_ - resource_name + Immutable. The full resource name of the Google Cloud resource + this asset represents. This field is immutable after create + time. See: https://cloud.google.com/apis/design/resource_names + #full_resource_name resource_type: - The type of the GCP resource. Examples include: APPLICATION, - PROJECT, and ORGANIZATION. This is a case insensitive field - defined by Cloud SCC and/or the producer of the resource and - is immutable after create time. + The type of the Google Cloud resource. Examples include: + APPLICATION, PROJECT, and ORGANIZATION. This is a case + insensitive field defined by Security Command Center and/or + the producer of the resource and is immutable after create + time. resource_parent: The full resource name of the immediate parent of the resource. See: https://cloud.google.com/apis/design/resource_n @@ -422,11 +425,11 @@ ), "DESCRIPTOR": _ASSET, "__module__": "google.cloud.securitycenter_v1beta1.proto.asset_pb2", - "__doc__": """Cloud Security Command Center’s (Cloud SCC) representation of a Google - Cloud Platform (GCP) resource. The Asset is a Cloud SCC resource that - captures information about a single GCP resource. All modifications to - an Asset are only within the context of Cloud SCC and don’t affect the - referenced GCP resource. + "__doc__": """Security Command Center representation of a Google Cloud resource. + The Asset is a Security Command Center resource that captures + information about a single Google Cloud resource. All modifications to + an Asset are only within the context of Security Command Center and + don’t affect the referenced Google Cloud resource. Attributes: name: @@ -434,21 +437,23 @@ oogle.com/apis/design/resource_names#relative_resource_name Example: “organizations/{organization_id}/assets/{asset_id}”. security_center_properties: - Cloud SCC managed properties. These properties are managed by - Cloud SCC and cannot be modified by the user. + Security Command Center managed properties. These properties + are managed by Security Command Center and cannot be modified + by the user. resource_properties: Resource managed properties. These properties are managed and - defined by the GCP resource and cannot be modified by the - user. + defined by the Google Cloud resource and cannot be modified by + the user. security_marks: User specified security marks. These marks are entirely managed by the user and come from the SecurityMarks resource that belongs to the asset. create_time: - The time at which the asset was created in Cloud SCC. + The time at which the asset was created in Security Command + Center. update_time: The time at which the asset was last updated, added, or - deleted in Cloud SCC. + deleted in Security Command Center. """, # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.Asset) }, @@ -461,4 +466,5 @@ DESCRIPTOR._options = None _ASSET_SECURITYCENTERPROPERTIES.fields_by_name["resource_name"]._options = None _ASSET_RESOURCEPROPERTIESENTRY._options = None +_ASSET._options = None # @@protoc_insertion_point(module_scope) diff --git a/google/cloud/securitycenter_v1beta1/proto/finding.proto b/google/cloud/securitycenter_v1beta1/proto/finding.proto index e582e6de..d78a522b 100644 --- a/google/cloud/securitycenter_v1beta1/proto/finding.proto +++ b/google/cloud/securitycenter_v1beta1/proto/finding.proto @@ -1,4 +1,4 @@ -// Copyright 2019 Google LLC. +// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -11,7 +11,6 @@ // 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. -// syntax = "proto3"; @@ -28,12 +27,12 @@ option go_package = "google.golang.org/genproto/googleapis/cloud/securitycenter/ option java_multiple_files = true; option java_package = "com.google.cloud.securitycenter.v1beta1"; -// Cloud Security Command Center (Cloud SCC) finding. +// Security Command Center finding. // // A finding is a record of assessment data (security, risk, health or privacy) -// ingested into Cloud SCC for presentation, notification, analysis, -// policy testing, and enforcement. For example, an XSS vulnerability in an -// App Engine application is a finding. +// ingested into Security Command Center for presentation, notification, +// analysis, policy testing, and enforcement. For example, an XSS vulnerability +// in an App Engine application is a finding. message Finding { option (google.api.resource) = { type: "securitycenter.googleapis.com/Finding" @@ -66,12 +65,12 @@ message Finding { // "organizations/{organization_id}/sources/{source_id}" string parent = 2 [(google.api.field_behavior) = IMMUTABLE]; - // For findings on Google Cloud Platform (GCP) resources, the full resource - // name of the GCP resource this finding is for. See: + // For findings on Google Cloud resources, the full resource + // name of the Google Cloud resource this finding is for. See: // https://cloud.google.com/apis/design/resource_names#full_resource_name - // When the finding is for a non-GCP resource, the resourceName can be a - // customer or partner defined string. - // This field is immutable after creation time. + // When the finding is for a non-Google Cloud resource, the resourceName can + // be a customer or partner defined string. This field is immutable after + // creation time. string resource_name = 3; // The state of the finding. @@ -82,9 +81,9 @@ message Finding { // Example: "XSS_FLASH_INJECTION" string category = 5; - // The URI that, if available, points to a web page outside of Cloud SCC - // where additional information about the finding can be found. This field is - // guaranteed to be either empty or a well formed URL. + // The URI that, if available, points to a web page outside of Security + // Command Center where additional information about the finding can be found. + // This field is guaranteed to be either empty or a well formed URL. string external_uri = 6; // Source specific properties. These properties are managed by the source @@ -103,6 +102,6 @@ message Finding { // the firewall became open. The accuracy is determined by the detector. google.protobuf.Timestamp event_time = 9; - // The time at which the finding was created in Cloud SCC. + // The time at which the finding was created in Security Command Center. google.protobuf.Timestamp create_time = 10; } diff --git a/google/cloud/securitycenter_v1beta1/proto/finding_pb2.py b/google/cloud/securitycenter_v1beta1/proto/finding_pb2.py index 0c7b8e81..f2620c16 100644 --- a/google/cloud/securitycenter_v1beta1/proto/finding_pb2.py +++ b/google/cloud/securitycenter_v1beta1/proto/finding_pb2.py @@ -388,9 +388,9 @@ ), "DESCRIPTOR": _FINDING, "__module__": "google.cloud.securitycenter_v1beta1.proto.finding_pb2", - "__doc__": """Cloud Security Command Center (Cloud SCC) finding. A finding is a - record of assessment data (security, risk, health or privacy) ingested - into Cloud SCC for presentation, notification, analysis, policy + "__doc__": """Security Command Center finding. A finding is a record of assessment + data (security, risk, health or privacy) ingested into Security + Command Center for presentation, notification, analysis, policy testing, and enforcement. For example, an XSS vulnerability in an App Engine application is a finding. @@ -407,10 +407,10 @@ after creation time. For example: “organizations/{organization_id}/sources/{source_id}” resource_name: - For findings on Google Cloud Platform (GCP) resources, the - full resource name of the GCP resource this finding is for. - See: https://cloud.google.com/apis/design/resource_names#full_ - resource_name When the finding is for a non-GCP resource, the + For findings on Google Cloud resources, the full resource name + of the Google Cloud resource this finding is for. See: https:/ + /cloud.google.com/apis/design/resource_names#full_resource_nam + e When the finding is for a non-Google Cloud resource, the resourceName can be a customer or partner defined string. This field is immutable after creation time. state: @@ -421,9 +421,9 @@ “XSS_FLASH_INJECTION” external_uri: The URI that, if available, points to a web page outside of - Cloud SCC where additional information about the finding can - be found. This field is guaranteed to be either empty or a - well formed URL. + Security Command Center where additional information about the + finding can be found. This field is guaranteed to be either + empty or a well formed URL. source_properties: Source specific properties. These properties are managed by the source that writes the finding. The key names in the @@ -440,7 +440,8 @@ the detector believes the firewall became open. The accuracy is determined by the detector. create_time: - The time at which the finding was created in Cloud SCC. + The time at which the finding was created in Security Command + Center. """, # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.Finding) }, diff --git a/google/cloud/securitycenter_v1beta1/proto/organization_settings.proto b/google/cloud/securitycenter_v1beta1/proto/organization_settings.proto index 9f7f2b0e..88b2008a 100644 --- a/google/cloud/securitycenter_v1beta1/proto/organization_settings.proto +++ b/google/cloud/securitycenter_v1beta1/proto/organization_settings.proto @@ -1,4 +1,4 @@ -// Copyright 2019 Google LLC. +// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -11,7 +11,6 @@ // 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. -// syntax = "proto3"; @@ -24,8 +23,8 @@ option go_package = "google.golang.org/genproto/googleapis/cloud/securitycenter/ option java_multiple_files = true; option java_package = "com.google.cloud.securitycenter.v1beta1"; -// User specified settings that are attached to the Cloud Security Command -// Center (Cloud SCC) organization. +// User specified settings that are attached to the Security Command +// Center organization. message OrganizationSettings { option (google.api.resource) = { type: "securitycenter.googleapis.com/OrganizationSettings" diff --git a/google/cloud/securitycenter_v1beta1/proto/organization_settings_pb2.py b/google/cloud/securitycenter_v1beta1/proto/organization_settings_pb2.py index 779190be..1d6fdb84 100644 --- a/google/cloud/securitycenter_v1beta1/proto/organization_settings_pb2.py +++ b/google/cloud/securitycenter_v1beta1/proto/organization_settings_pb2.py @@ -243,8 +243,8 @@ ), "DESCRIPTOR": _ORGANIZATIONSETTINGS, "__module__": "google.cloud.securitycenter_v1beta1.proto.organization_settings_pb2", - "__doc__": """User specified settings that are attached to the Cloud Security - Command Center (Cloud SCC) organization. + "__doc__": """User specified settings that are attached to the Security Command + Center organization. Attributes: name: diff --git a/google/cloud/securitycenter_v1beta1/proto/run_asset_discovery_response.proto b/google/cloud/securitycenter_v1beta1/proto/run_asset_discovery_response.proto index 53ba02ef..20d3b25b 100644 --- a/google/cloud/securitycenter_v1beta1/proto/run_asset_discovery_response.proto +++ b/google/cloud/securitycenter_v1beta1/proto/run_asset_discovery_response.proto @@ -1,4 +1,4 @@ -// Copyright 2019 Google LLC. +// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -11,7 +11,6 @@ // 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. -// syntax = "proto3"; diff --git a/google/cloud/securitycenter_v1beta1/proto/security_marks.proto b/google/cloud/securitycenter_v1beta1/proto/security_marks.proto index 97baf247..2547c306 100644 --- a/google/cloud/securitycenter_v1beta1/proto/security_marks.proto +++ b/google/cloud/securitycenter_v1beta1/proto/security_marks.proto @@ -1,4 +1,4 @@ -// Copyright 2019 Google LLC. +// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -11,7 +11,6 @@ // 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. -// syntax = "proto3"; @@ -24,9 +23,9 @@ option go_package = "google.golang.org/genproto/googleapis/cloud/securitycenter/ option java_multiple_files = true; option java_package = "com.google.cloud.securitycenter.v1beta1"; -// User specified security marks that are attached to the parent Cloud Security -// Command Center (Cloud SCC) resource. Security marks are scoped within a Cloud -// SCC organization -- they can be modified and viewed by all users who have +// User specified security marks that are attached to the parent Security +// Command Center resource. Security marks are scoped within a Security Command +// Center organization -- they can be modified and viewed by all users who have // proper permissions on the organization. message SecurityMarks { option (google.api.resource) = { diff --git a/google/cloud/securitycenter_v1beta1/proto/security_marks_pb2.py b/google/cloud/securitycenter_v1beta1/proto/security_marks_pb2.py index a9cae49e..558b3e3a 100644 --- a/google/cloud/securitycenter_v1beta1/proto/security_marks_pb2.py +++ b/google/cloud/securitycenter_v1beta1/proto/security_marks_pb2.py @@ -168,10 +168,10 @@ ), "DESCRIPTOR": _SECURITYMARKS, "__module__": "google.cloud.securitycenter_v1beta1.proto.security_marks_pb2", - "__doc__": """User specified security marks that are attached to the parent Cloud - Security Command Center (Cloud SCC) resource. Security marks are - scoped within a Cloud SCC organization – they can be modified and - viewed by all users who have proper permissions on the organization. + "__doc__": """User specified security marks that are attached to the parent Security + Command Center resource. Security marks are scoped within a Security + Command Center organization – they can be modified and viewed by all + users who have proper permissions on the organization. Attributes: name: diff --git a/google/cloud/securitycenter_v1beta1/proto/securitycenter_service.proto b/google/cloud/securitycenter_v1beta1/proto/securitycenter_service.proto index ba2edf4e..351c1f4a 100644 --- a/google/cloud/securitycenter_v1beta1/proto/securitycenter_service.proto +++ b/google/cloud/securitycenter_v1beta1/proto/securitycenter_service.proto @@ -1,4 +1,4 @@ -// Copyright 2019 Google LLC. +// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -11,7 +11,6 @@ // 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. -// syntax = "proto3"; diff --git a/google/cloud/securitycenter_v1beta1/proto/source.proto b/google/cloud/securitycenter_v1beta1/proto/source.proto index 98025bca..fb1e6c6a 100644 --- a/google/cloud/securitycenter_v1beta1/proto/source.proto +++ b/google/cloud/securitycenter_v1beta1/proto/source.proto @@ -1,4 +1,4 @@ -// Copyright 2019 Google LLC. +// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. @@ -11,7 +11,6 @@ // 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. -// syntax = "proto3"; @@ -24,7 +23,7 @@ option go_package = "google.golang.org/genproto/googleapis/cloud/securitycenter/ option java_multiple_files = true; option java_package = "com.google.cloud.securitycenter.v1beta1"; -// Cloud Security Command Center's (Cloud SCC) finding source. A finding source +// Security Command Center finding source. A finding source // is an entity or a mechanism that can produce a finding. A source is like a // container of findings that come from the same scanner, logger, monitor, etc. message Source { @@ -48,7 +47,7 @@ message Source { // The description of the source (max of 1024 characters). // Example: - // "Cloud Security Scanner is a web security scanner for common + // "Web Security Scanner is a web security scanner for common // vulnerabilities in App Engine applications. It can automatically // scan and detect four common vulnerabilities, including cross-site-scripting // (XSS), Flash injection, mixed content (HTTP in HTTPS), and diff --git a/google/cloud/securitycenter_v1beta1/proto/source_pb2.py b/google/cloud/securitycenter_v1beta1/proto/source_pb2.py index 835fccd5..886c0336 100644 --- a/google/cloud/securitycenter_v1beta1/proto/source_pb2.py +++ b/google/cloud/securitycenter_v1beta1/proto/source_pb2.py @@ -117,10 +117,10 @@ { "DESCRIPTOR": _SOURCE, "__module__": "google.cloud.securitycenter_v1beta1.proto.source_pb2", - "__doc__": """Cloud Security Command Center’s (Cloud SCC) finding source. A finding - source is an entity or a mechanism that can produce a finding. A - source is like a container of findings that come from the same - scanner, logger, monitor, etc. + "__doc__": """Security Command Center finding source. A finding source is an entity + or a mechanism that can produce a finding. A source is like a + container of findings that come from the same scanner, logger, + monitor, etc. Attributes: name: @@ -135,7 +135,7 @@ (inclusive). description: The description of the source (max of 1024 characters). - Example: “Cloud Security Scanner is a web security scanner for + Example: “Web Security Scanner is a web security scanner for common vulnerabilities in App Engine applications. It can automatically scan and detect four common vulnerabilities, including cross-site-scripting (XSS), Flash injection, mixed diff --git a/synth.metadata b/synth.metadata index 23f3e9f8..12fd89b0 100644 --- a/synth.metadata +++ b/synth.metadata @@ -11,8 +11,8 @@ "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "9362f58401cfe3b463b75a18d134bb818ad4dcb2", - "internalRef": "321179885" + "sha": "e26e1839a45445d13cd45b1be3b1523defb72fee", + "internalRef": "322867095" } }, { From f50ff9117d8e0d381930855fe40ccb93c8174c9a Mon Sep 17 00:00:00 2001 From: yoshi-automation Date: Sat, 1 Aug 2020 11:21:12 -0700 Subject: [PATCH 05/17] fix!: migrate securitycenter/v1beta1 to gapic v2 BREAKING CHANGE: IAM method flattenings changed to generic resource name class PiperOrigin-RevId: 323062460 Source-Author: Google APIs Source-Date: Fri Jul 24 13:35:34 2020 -0700 Source-Repo: googleapis/googleapis Source-Sha: 599ede9ebdeb33a91be48748f5f83ec13e7e692c Source-Link: https://github.com/googleapis/googleapis/commit/599ede9ebdeb33a91be48748f5f83ec13e7e692c --- .../gapic/security_center_client.py | 37 ++--- .../gapic/security_center_client_config.py | 135 +++++++++++------- synth.metadata | 4 +- .../test_security_center_client_v1beta1.py | 12 +- 4 files changed, 110 insertions(+), 78 deletions(-) diff --git a/google/cloud/securitycenter_v1beta1/gapic/security_center_client.py b/google/cloud/securitycenter_v1beta1/gapic/security_center_client.py index 72660006..bc638425 100644 --- a/google/cloud/securitycenter_v1beta1/gapic/security_center_client.py +++ b/google/cloud/securitycenter_v1beta1/gapic/security_center_client.py @@ -89,15 +89,6 @@ def from_service_account_file(cls, filename, *args, **kwargs): from_service_account_json = from_service_account_file - @classmethod - def asset_security_marks_path(cls, organization, asset): - """Return a fully-qualified asset_security_marks string.""" - return google.api_core.path_template.expand( - "organizations/{organization}/assets/{asset}/securityMarks", - organization=organization, - asset=asset, - ) - @classmethod def finding_path(cls, organization, source, finding): """Return a fully-qualified finding string.""" @@ -108,16 +99,6 @@ def finding_path(cls, organization, source, finding): finding=finding, ) - @classmethod - def finding_security_marks_path(cls, organization, source, finding): - """Return a fully-qualified finding_security_marks string.""" - return google.api_core.path_template.expand( - "organizations/{organization}/sources/{source}/findings/{finding}/securityMarks", - organization=organization, - source=source, - finding=finding, - ) - @classmethod def organization_path(cls, organization): """Return a fully-qualified organization string.""" @@ -133,6 +114,15 @@ def organization_settings_path(cls, organization): organization=organization, ) + @classmethod + def security_marks_path(cls, organization, asset): + """Return a fully-qualified security_marks string.""" + return google.api_core.path_template.expand( + "organizations/{organization}/assets/{asset}/securityMarks", + organization=organization, + asset=asset, + ) + @classmethod def source_path(cls, organization, source): """Return a fully-qualified source string.""" @@ -441,7 +431,8 @@ def get_iam_policy( >>> >>> client = securitycenter_v1beta1.SecurityCenterClient() >>> - >>> resource = client.source_path('[ORGANIZATION]', '[SOURCE]') + >>> # TODO: Initialize `resource`: + >>> resource = '' >>> >>> response = client.get_iam_policy(resource) @@ -1647,7 +1638,8 @@ def set_iam_policy( >>> >>> client = securitycenter_v1beta1.SecurityCenterClient() >>> - >>> resource = client.source_path('[ORGANIZATION]', '[SOURCE]') + >>> # TODO: Initialize `resource`: + >>> resource = '' >>> >>> # TODO: Initialize `policy`: >>> policy = {} @@ -1728,7 +1720,8 @@ def test_iam_permissions( >>> >>> client = securitycenter_v1beta1.SecurityCenterClient() >>> - >>> resource = client.source_path('[ORGANIZATION]', '[SOURCE]') + >>> # TODO: Initialize `resource`: + >>> resource = '' >>> >>> # TODO: Initialize `permissions`: >>> permissions = [] diff --git a/google/cloud/securitycenter_v1beta1/gapic/security_center_client_config.py b/google/cloud/securitycenter_v1beta1/gapic/security_center_client_config.py index 9b5c01a9..6d6b421b 100644 --- a/google/cloud/securitycenter_v1beta1/gapic/security_center_client_config.py +++ b/google/cloud/securitycenter_v1beta1/gapic/security_center_client_config.py @@ -2,110 +2,149 @@ "interfaces": { "google.cloud.securitycenter.v1beta1.SecurityCenter": { "retry_codes": { - "idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "non_idempotent": [], + "retry_policy_1_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], + "no_retry_2_codes": [], + "no_retry_codes": [], + "retry_policy_2_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], + "no_retry_1_codes": [], }, "retry_params": { - "default": { + "retry_policy_1_params": { "initial_retry_delay_millis": 100, "retry_delay_multiplier": 1.3, "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 20000, + "initial_rpc_timeout_millis": 60000, "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 20000, - "total_timeout_millis": 600000, - } + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 60000, + }, + "retry_policy_2_params": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 480000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 480000, + "total_timeout_millis": 480000, + }, + "no_retry_params": { + "initial_retry_delay_millis": 0, + "retry_delay_multiplier": 0.0, + "max_retry_delay_millis": 0, + "initial_rpc_timeout_millis": 0, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 0, + "total_timeout_millis": 0, + }, + "no_retry_1_params": { + "initial_retry_delay_millis": 0, + "retry_delay_multiplier": 0.0, + "max_retry_delay_millis": 0, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 60000, + }, + "no_retry_2_params": { + "initial_retry_delay_millis": 0, + "retry_delay_multiplier": 0.0, + "max_retry_delay_millis": 0, + "initial_rpc_timeout_millis": 480000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 480000, + "total_timeout_millis": 480000, + }, }, "methods": { "CreateSource": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "CreateFinding": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "GetIamPolicy": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "GetOrganizationSettings": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "GetSource": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "GroupAssets": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "timeout_millis": 480000, + "retry_codes_name": "retry_policy_2_codes", + "retry_params_name": "retry_policy_2_params", }, "GroupFindings": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "timeout_millis": 480000, + "retry_codes_name": "retry_policy_2_codes", + "retry_params_name": "retry_policy_2_params", }, "ListAssets": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "timeout_millis": 480000, + "retry_codes_name": "retry_policy_2_codes", + "retry_params_name": "retry_policy_2_params", }, "ListFindings": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "timeout_millis": 480000, + "retry_codes_name": "retry_policy_2_codes", + "retry_params_name": "retry_policy_2_params", }, "ListSources": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "RunAssetDiscovery": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "SetFindingState": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "SetIamPolicy": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "TestIamPermissions": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "UpdateFinding": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "UpdateOrganizationSettings": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "UpdateSource": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "UpdateSecurityMarks": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "timeout_millis": 480000, + "retry_codes_name": "no_retry_2_codes", + "retry_params_name": "no_retry_2_params", }, }, } diff --git a/synth.metadata b/synth.metadata index 12fd89b0..7d71d26b 100644 --- a/synth.metadata +++ b/synth.metadata @@ -11,8 +11,8 @@ "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "e26e1839a45445d13cd45b1be3b1523defb72fee", - "internalRef": "322867095" + "sha": "599ede9ebdeb33a91be48748f5f83ec13e7e692c", + "internalRef": "323062460" } }, { diff --git a/tests/unit/gapic/v1beta1/test_security_center_client_v1beta1.py b/tests/unit/gapic/v1beta1/test_security_center_client_v1beta1.py index bab98fc9..3cc4f388 100644 --- a/tests/unit/gapic/v1beta1/test_security_center_client_v1beta1.py +++ b/tests/unit/gapic/v1beta1/test_security_center_client_v1beta1.py @@ -189,7 +189,7 @@ def test_get_iam_policy(self): client = securitycenter_v1beta1.SecurityCenterClient() # Setup Request - resource = client.source_path("[ORGANIZATION]", "[SOURCE]") + resource = "resource-341064690" response = client.get_iam_policy(resource) assert expected_response == response @@ -208,7 +208,7 @@ def test_get_iam_policy_exception(self): client = securitycenter_v1beta1.SecurityCenterClient() # Setup request - resource = client.source_path("[ORGANIZATION]", "[SOURCE]") + resource = "resource-341064690" with pytest.raises(CustomException): client.get_iam_policy(resource) @@ -673,7 +673,7 @@ def test_set_iam_policy(self): client = securitycenter_v1beta1.SecurityCenterClient() # Setup Request - resource = client.source_path("[ORGANIZATION]", "[SOURCE]") + resource = "resource-341064690" policy = {} response = client.set_iam_policy(resource, policy) @@ -695,7 +695,7 @@ def test_set_iam_policy_exception(self): client = securitycenter_v1beta1.SecurityCenterClient() # Setup request - resource = client.source_path("[ORGANIZATION]", "[SOURCE]") + resource = "resource-341064690" policy = {} with pytest.raises(CustomException): @@ -716,7 +716,7 @@ def test_test_iam_permissions(self): client = securitycenter_v1beta1.SecurityCenterClient() # Setup Request - resource = client.source_path("[ORGANIZATION]", "[SOURCE]") + resource = "resource-341064690" permissions = [] response = client.test_iam_permissions(resource, permissions) @@ -738,7 +738,7 @@ def test_test_iam_permissions_exception(self): client = securitycenter_v1beta1.SecurityCenterClient() # Setup request - resource = client.source_path("[ORGANIZATION]", "[SOURCE]") + resource = "resource-341064690" permissions = [] with pytest.raises(CustomException): From 35979bb91540047947cd0c3066fb11d670ac2457 Mon Sep 17 00:00:00 2001 From: yoshi-automation Date: Sat, 1 Aug 2020 11:23:12 -0700 Subject: [PATCH 06/17] chore: migrate securitycenter to python microgenerator PiperOrigin-RevId: 323472217 Source-Author: Google APIs Source-Date: Mon Jul 27 17:03:43 2020 -0700 Source-Repo: googleapis/googleapis Source-Sha: 6a813acf535e4746fa4a135ce23547bb6425c26d Source-Link: https://github.com/googleapis/googleapis/commit/6a813acf535e4746fa4a135ce23547bb6425c26d --- docs/gapic/v1beta1/api.rst | 4 +- docs/gapic/v1beta1/types.rst | 4 +- google/cloud/securitycenter_v1/__init__.py | 102 +- .../gapic/security_center_client.py | 1300 ++++----- .../gapic/security_center_client_config.py | 169 +- .../security_center_grpc_transport.py | 114 +- google/cloud/securitycenter_v1/py.typed | 2 + .../securitycenter_v1/services/__init__.py | 16 + .../services/security_center/__init__.py | 24 + .../services/security_center/async_client.py | 2226 +++++++++++++++ .../services/security_center/client.py | 2416 ++++++++++++++++ .../services/security_center/pagers.py | 804 ++++++ .../security_center/transports/__init__.py | 36 + .../security_center/transports/base.py | 354 +++ .../security_center/transports/grpc.py | 900 ++++++ .../transports/grpc_asyncio.py | 905 ++++++ .../cloud/securitycenter_v1/types/__init__.py | 95 + google/cloud/securitycenter_v1/types/asset.py | 166 ++ .../cloud/securitycenter_v1/types/finding.py | 123 + .../types/notification_config.py | 100 + .../types/notification_message.py | 54 + .../types/organization_settings.py | 89 + .../cloud/securitycenter_v1/types/resource.py | 56 + .../types/run_asset_discovery_response.py | 52 + .../securitycenter_v1/types/security_marks.py | 57 + .../types/securitycenter_service.py | 1353 +++++++++ .../cloud/securitycenter_v1/types/source.py | 64 + .../cloud/securitycenter_v1beta1/__init__.py | 84 +- .../gapic/security_center_client.py | 37 +- .../gapic/security_center_client_config.py | 135 +- .../securitycenter_v1beta1/proto/asset_pb2.py | 64 +- .../proto/finding_pb2.py | 23 +- .../proto/organization_settings_pb2.py | 4 +- .../proto/security_marks_pb2.py | 8 +- .../proto/source_pb2.py | 10 +- google/cloud/securitycenter_v1beta1/py.typed | 2 + .../services/__init__.py | 16 + .../services/security_center/__init__.py | 24 + .../services/security_center/async_client.py | 1801 ++++++++++++ .../services/security_center/client.py | 1979 +++++++++++++ .../services/security_center/pagers.py | 668 +++++ .../security_center/transports/__init__.py | 36 + .../security_center/transports/base.py | 294 ++ .../security_center/transports/grpc.py | 754 +++++ .../transports/grpc_asyncio.py | 759 +++++ .../securitycenter_v1beta1/types/__init__.py | 77 + .../securitycenter_v1beta1/types/asset.py | 129 + .../securitycenter_v1beta1/types/finding.py | 125 + .../types/organization_settings.py | 89 + .../types/run_asset_discovery_response.py | 53 + .../types/security_marks.py | 57 + .../types/securitycenter_service.py | 862 ++++++ .../securitycenter_v1beta1/types/source.py | 64 + .../securitycenter_v1p1beta1/__init__.py | 102 +- .../gapic/security_center_client_config.py | 155 +- .../cloud/securitycenter_v1p1beta1/py.typed | 2 + .../services/__init__.py | 16 + .../services/security_center/__init__.py | 24 + .../services/security_center/async_client.py | 2317 +++++++++++++++ .../services/security_center/client.py | 2507 +++++++++++++++++ .../services/security_center/pagers.py | 804 ++++++ .../security_center/transports/__init__.py | 36 + .../security_center/transports/base.py | 356 +++ .../security_center/transports/grpc.py | 904 ++++++ .../transports/grpc_asyncio.py | 909 ++++++ .../types/__init__.py | 95 + .../securitycenter_v1p1beta1/types/asset.py | 168 ++ .../securitycenter_v1p1beta1/types/finding.py | 125 + .../types/notification_config.py | 109 + .../types/notification_message.py | 53 + .../types/organization_settings.py | 89 + .../types/resource.py | 56 + .../types/run_asset_discovery_response.py | 53 + .../types/security_marks.py | 57 + .../types/securitycenter_service.py | 1356 +++++++++ .../securitycenter_v1p1beta1/types/source.py | 64 + synth.metadata | 4 +- .../v1/test_security_center_client_v1.py | 380 +-- .../test_security_center_client_v1beta1.py | 12 +- 79 files changed, 29144 insertions(+), 1348 deletions(-) create mode 100644 google/cloud/securitycenter_v1/py.typed create mode 100644 google/cloud/securitycenter_v1/services/__init__.py create mode 100644 google/cloud/securitycenter_v1/services/security_center/__init__.py create mode 100644 google/cloud/securitycenter_v1/services/security_center/async_client.py create mode 100644 google/cloud/securitycenter_v1/services/security_center/client.py create mode 100644 google/cloud/securitycenter_v1/services/security_center/pagers.py create mode 100644 google/cloud/securitycenter_v1/services/security_center/transports/__init__.py create mode 100644 google/cloud/securitycenter_v1/services/security_center/transports/base.py create mode 100644 google/cloud/securitycenter_v1/services/security_center/transports/grpc.py create mode 100644 google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py create mode 100644 google/cloud/securitycenter_v1/types/__init__.py create mode 100644 google/cloud/securitycenter_v1/types/asset.py create mode 100644 google/cloud/securitycenter_v1/types/finding.py create mode 100644 google/cloud/securitycenter_v1/types/notification_config.py create mode 100644 google/cloud/securitycenter_v1/types/notification_message.py create mode 100644 google/cloud/securitycenter_v1/types/organization_settings.py create mode 100644 google/cloud/securitycenter_v1/types/resource.py create mode 100644 google/cloud/securitycenter_v1/types/run_asset_discovery_response.py create mode 100644 google/cloud/securitycenter_v1/types/security_marks.py create mode 100644 google/cloud/securitycenter_v1/types/securitycenter_service.py create mode 100644 google/cloud/securitycenter_v1/types/source.py create mode 100644 google/cloud/securitycenter_v1beta1/py.typed create mode 100644 google/cloud/securitycenter_v1beta1/services/__init__.py create mode 100644 google/cloud/securitycenter_v1beta1/services/security_center/__init__.py create mode 100644 google/cloud/securitycenter_v1beta1/services/security_center/async_client.py create mode 100644 google/cloud/securitycenter_v1beta1/services/security_center/client.py create mode 100644 google/cloud/securitycenter_v1beta1/services/security_center/pagers.py create mode 100644 google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py create mode 100644 google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py create mode 100644 google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py create mode 100644 google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py create mode 100644 google/cloud/securitycenter_v1beta1/types/__init__.py create mode 100644 google/cloud/securitycenter_v1beta1/types/asset.py create mode 100644 google/cloud/securitycenter_v1beta1/types/finding.py create mode 100644 google/cloud/securitycenter_v1beta1/types/organization_settings.py create mode 100644 google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py create mode 100644 google/cloud/securitycenter_v1beta1/types/security_marks.py create mode 100644 google/cloud/securitycenter_v1beta1/types/securitycenter_service.py create mode 100644 google/cloud/securitycenter_v1beta1/types/source.py create mode 100644 google/cloud/securitycenter_v1p1beta1/py.typed create mode 100644 google/cloud/securitycenter_v1p1beta1/services/__init__.py create mode 100644 google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py create mode 100644 google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py create mode 100644 google/cloud/securitycenter_v1p1beta1/services/security_center/client.py create mode 100644 google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py create mode 100644 google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py create mode 100644 google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py create mode 100644 google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py create mode 100644 google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py create mode 100644 google/cloud/securitycenter_v1p1beta1/types/__init__.py create mode 100644 google/cloud/securitycenter_v1p1beta1/types/asset.py create mode 100644 google/cloud/securitycenter_v1p1beta1/types/finding.py create mode 100644 google/cloud/securitycenter_v1p1beta1/types/notification_config.py create mode 100644 google/cloud/securitycenter_v1p1beta1/types/notification_message.py create mode 100644 google/cloud/securitycenter_v1p1beta1/types/organization_settings.py create mode 100644 google/cloud/securitycenter_v1p1beta1/types/resource.py create mode 100644 google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py create mode 100644 google/cloud/securitycenter_v1p1beta1/types/security_marks.py create mode 100644 google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py create mode 100644 google/cloud/securitycenter_v1p1beta1/types/source.py diff --git a/docs/gapic/v1beta1/api.rst b/docs/gapic/v1beta1/api.rst index 89fdb487..5bf656fe 100644 --- a/docs/gapic/v1beta1/api.rst +++ b/docs/gapic/v1beta1/api.rst @@ -1,5 +1,5 @@ -Client for Security Command Center API -====================================== +Client for Cloud Security Command Center API +============================================ .. automodule:: google.cloud.securitycenter_v1beta1 :members: diff --git a/docs/gapic/v1beta1/types.rst b/docs/gapic/v1beta1/types.rst index 1ec286a2..4af19d8c 100644 --- a/docs/gapic/v1beta1/types.rst +++ b/docs/gapic/v1beta1/types.rst @@ -1,5 +1,5 @@ -Types for Security Command Center API Client -============================================ +Types for Cloud Security Command Center API Client +================================================== .. automodule:: google.cloud.securitycenter_v1beta1.types :members: \ No newline at end of file diff --git a/google/cloud/securitycenter_v1/__init__.py b/google/cloud/securitycenter_v1/__init__.py index e7f67b46..27c3ed04 100644 --- a/google/cloud/securitycenter_v1/__init__.py +++ b/google/cloud/securitycenter_v1/__init__.py @@ -1,45 +1,95 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 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 +# 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 absolute_import -import sys -import warnings - -from google.cloud.securitycenter_v1 import types -from google.cloud.securitycenter_v1.gapic import enums -from google.cloud.securitycenter_v1.gapic import security_center_client - - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7. " - "More details about Python 2 support for Google Cloud Client Libraries " - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) - - -class SecurityCenterClient(security_center_client.SecurityCenterClient): - __doc__ = security_center_client.SecurityCenterClient.__doc__ - enums = enums +from .services.security_center import SecurityCenterClient +from .types.asset import Asset +from .types.finding import Finding +from .types.notification_config import NotificationConfig +from .types.notification_message import NotificationMessage +from .types.organization_settings import OrganizationSettings +from .types.resource import Resource +from .types.run_asset_discovery_response import RunAssetDiscoveryResponse +from .types.security_marks import SecurityMarks +from .types.securitycenter_service import CreateFindingRequest +from .types.securitycenter_service import CreateNotificationConfigRequest +from .types.securitycenter_service import CreateSourceRequest +from .types.securitycenter_service import DeleteNotificationConfigRequest +from .types.securitycenter_service import GetNotificationConfigRequest +from .types.securitycenter_service import GetOrganizationSettingsRequest +from .types.securitycenter_service import GetSourceRequest +from .types.securitycenter_service import GroupAssetsRequest +from .types.securitycenter_service import GroupAssetsResponse +from .types.securitycenter_service import GroupFindingsRequest +from .types.securitycenter_service import GroupFindingsResponse +from .types.securitycenter_service import GroupResult +from .types.securitycenter_service import ListAssetsRequest +from .types.securitycenter_service import ListAssetsResponse +from .types.securitycenter_service import ListFindingsRequest +from .types.securitycenter_service import ListFindingsResponse +from .types.securitycenter_service import ListNotificationConfigsRequest +from .types.securitycenter_service import ListNotificationConfigsResponse +from .types.securitycenter_service import ListSourcesRequest +from .types.securitycenter_service import ListSourcesResponse +from .types.securitycenter_service import RunAssetDiscoveryRequest +from .types.securitycenter_service import SetFindingStateRequest +from .types.securitycenter_service import UpdateFindingRequest +from .types.securitycenter_service import UpdateNotificationConfigRequest +from .types.securitycenter_service import UpdateOrganizationSettingsRequest +from .types.securitycenter_service import UpdateSecurityMarksRequest +from .types.securitycenter_service import UpdateSourceRequest +from .types.source import Source __all__ = ( - "enums", - "types", + "Asset", + "CreateFindingRequest", + "CreateNotificationConfigRequest", + "CreateSourceRequest", + "DeleteNotificationConfigRequest", + "Finding", + "GetNotificationConfigRequest", + "GetOrganizationSettingsRequest", + "GetSourceRequest", + "GroupAssetsRequest", + "GroupAssetsResponse", + "GroupFindingsRequest", + "GroupFindingsResponse", + "GroupResult", + "ListAssetsRequest", + "ListAssetsResponse", + "ListFindingsRequest", + "ListFindingsResponse", + "ListNotificationConfigsRequest", + "ListNotificationConfigsResponse", + "ListSourcesRequest", + "ListSourcesResponse", + "NotificationConfig", + "NotificationMessage", + "OrganizationSettings", + "Resource", + "RunAssetDiscoveryRequest", + "RunAssetDiscoveryResponse", + "SecurityMarks", + "SetFindingStateRequest", + "Source", + "UpdateFindingRequest", + "UpdateNotificationConfigRequest", + "UpdateOrganizationSettingsRequest", + "UpdateSecurityMarksRequest", + "UpdateSourceRequest", "SecurityCenterClient", ) diff --git a/google/cloud/securitycenter_v1/gapic/security_center_client.py b/google/cloud/securitycenter_v1/gapic/security_center_client.py index e6c19fcd..9c1f9104 100644 --- a/google/cloud/securitycenter_v1/gapic/security_center_client.py +++ b/google/cloud/securitycenter_v1/gapic/security_center_client.py @@ -282,37 +282,35 @@ def __init__( self._inner_api_calls = {} # Service calls - def create_source( + def get_iam_policy( self, - parent, - source, + resource, + options_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ - Creates a source. + Gets the access control policy on the specified Source. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> - >>> parent = client.organization_path('[ORGANIZATION]') - >>> - >>> # TODO: Initialize `source`: - >>> source = {} + >>> # TODO: Initialize `resource`: + >>> resource = '' >>> - >>> response = client.create_source(parent, source) + >>> response = client.get_iam_policy(resource) Args: - parent (str): Required. Resource name of the new source's parent. Its format - should be "organizations/[organization_id]". - source (Union[dict, ~google.cloud.securitycenter_v1.types.Source]): Required. The Source being created, only the display_name and - description will be used. All other fields will be ignored. + resource (str): REQUIRED: The resource for which the policy is being requested. + See the operation documentation for the appropriate value for this field. + options_ (Union[dict, ~google.cloud.securitycenter_v1.types.GetPolicyOptions]): OPTIONAL: A ``GetPolicyOptions`` object for specifying options to + ``GetIamPolicy``. This field is only used by Cloud IAM. If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Source` + message :class:`~google.cloud.securitycenter_v1.types.GetPolicyOptions` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -323,7 +321,7 @@ def create_source( that is provided to the method. Returns: - A :class:`~google.cloud.securitycenter_v1.types.Source` instance. + A :class:`~google.cloud.securitycenter_v1.types.Policy` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request @@ -333,24 +331,24 @@ def create_source( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "create_source" not in self._inner_api_calls: + if "get_iam_policy" not in self._inner_api_calls: self._inner_api_calls[ - "create_source" + "get_iam_policy" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_source, - default_retry=self._method_configs["CreateSource"].retry, - default_timeout=self._method_configs["CreateSource"].timeout, + self.transport.get_iam_policy, + default_retry=self._method_configs["GetIamPolicy"].retry, + default_timeout=self._method_configs["GetIamPolicy"].timeout, client_info=self._client_info, ) - request = securitycenter_service_pb2.CreateSourceRequest( - parent=parent, source=source, + request = iam_policy_pb2.GetIamPolicyRequest( + resource=resource, options=options_, ) if metadata is None: metadata = [] metadata = list(metadata) try: - routing_header = [("parent", parent)] + routing_header = [("resource", resource)] except AttributeError: pass else: @@ -359,49 +357,186 @@ def create_source( ) metadata.append(routing_metadata) - return self._inner_api_calls["create_source"]( + return self._inner_api_calls["get_iam_policy"]( request, retry=retry, timeout=timeout, metadata=metadata ) - def create_finding( + def group_assets( self, parent, - finding_id, - finding, + group_by, + filter_=None, + compare_duration=None, + read_time=None, + page_size=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ - Creates a finding. The corresponding source must exist for finding creation - to succeed. + Filters an organization's assets and groups them by their specified + properties. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> - >>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]') + >>> parent = client.organization_path('[ORGANIZATION]') >>> - >>> # TODO: Initialize `finding_id`: - >>> finding_id = '' + >>> # TODO: Initialize `group_by`: + >>> group_by = '' >>> - >>> # TODO: Initialize `finding`: - >>> finding = {} + >>> # Iterate over all results + >>> for element in client.group_assets(parent, group_by): + ... # process element + ... pass >>> - >>> response = client.create_finding(parent, finding_id, finding) + >>> + >>> # Alternatively: + >>> + >>> # Iterate over results one page at a time + >>> for page in client.group_assets(parent, group_by).pages: + ... for element in page: + ... # process element + ... pass Args: - parent (str): Required. Resource name of the new finding's parent. Its format - should be "organizations/[organization_id]/sources/[source_id]". - finding_id (str): Required. Unique identifier provided by the client within the parent scope. - It must be alphanumeric and less than or equal to 32 characters and - greater than 0 characters in length. - finding (Union[dict, ~google.cloud.securitycenter_v1.types.Finding]): Required. The Finding being created. The name and security_marks - will be ignored as they are both output only fields on this resource. + parent (str): Required. Name of the organization to groupBy. Its format is + "organizations/[organization_id]". + group_by (str): Required. Expression that defines what assets fields to use for + grouping. The string value should follow SQL syntax: comma separated + list of fields. For example: + "security_center_properties.resource_project,security_center_properties.project". + + The following fields are supported when compare_duration is not set: + + - security_center_properties.resource_project + - security_center_properties.resource_project_display_name + - security_center_properties.resource_type + - security_center_properties.resource_parent + - security_center_properties.resource_parent_display_name + + The following fields are supported when compare_duration is set: + + - security_center_properties.resource_type + - security_center_properties.resource_project_display_name + - security_center_properties.resource_parent_display_name + filter_ (str): Expression that defines the filter to apply across assets. The + expression is a list of zero or more restrictions combined via logical + operators ``AND`` and ``OR``. Parentheses are supported, and ``OR`` has + higher precedence than ``AND``. + + Restrictions have the form `` `` and may have a + ``-`` character in front of them to indicate negation. The fields map to + those defined in the Asset resource. Examples include: + + - name + - security_center_properties.resource_name + - resource_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an RFC3339 string. + Examples: ``update_time = "2019-06-10T16:07:18-07:00"`` + ``update_time = 1560208038000`` + + - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an RFC3339 string. + Examples: ``create_time = "2019-06-10T16:07:18-07:00"`` + ``create_time = 1560208038000`` + + - iam_policy.policy_blob: ``=``, ``:`` + + - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, ``<=`` + + - security_marks.marks: ``=``, ``:`` + + - security_center_properties.resource_name: ``=``, ``:`` + + - security_center_properties.resource_display_name: ``=``, ``:`` + + - security_center_properties.resource_type: ``=``, ``:`` + + - security_center_properties.resource_parent: ``=``, ``:`` + + - security_center_properties.resource_parent_display_name: ``=``, ``:`` + + - security_center_properties.resource_project: ``=``, ``:`` + + - security_center_properties.resource_project_display_name: ``=``, + ``:`` + + - security_center_properties.resource_owners: ``=``, ``:`` + + For example, ``resource_properties.size = 100`` is a valid filter + string. + + Use a partial match on the empty string to filter based on a property + existing:\ ``resource_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter based on a + property not existing: ``-resource_properties.my_property : ""`` + compare_duration (Union[dict, ~google.cloud.securitycenter_v1.types.Duration]): When compare_duration is set, the GroupResult's "state_change" + property is updated to indicate whether the asset was added, removed, or + remained present during the compare_duration period of time that + precedes the read_time. This is the time between (read_time - + compare_duration) and read_time. + + The state change value is derived based on the presence of the asset at + the two points in time. Intermediate state changes between the two times + don't affect the result. For example, the results aren't affected if the + asset is removed and re-created again. + + Possible "state_change" values when compare_duration is specified: + + - "ADDED": indicates that the asset was not present at the start of + compare_duration, but present at reference_time. + - "REMOVED": indicates that the asset was present at the start of + compare_duration, but not present at reference_time. + - "ACTIVE": indicates that the asset was present at both the start and + the end of the time period defined by compare_duration and + reference_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set for all + assets present at read_time. + + If this field is set then ``state_change`` must be a specified field in + ``group_by``. If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Finding` + message :class:`~google.cloud.securitycenter_v1.types.Duration` + read_time (Union[dict, ~google.cloud.securitycenter_v1.types.Timestamp]): Time used as a reference point when filtering assets. The filter is limited + to assets existing at the supplied time and their values are those at that + specific time. Absence of this field will default to the API's version of + NOW. + + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.securitycenter_v1.types.Timestamp` + page_size (int): The maximum number of resources contained in the + underlying API response. If page streaming is performed per- + resource, this parameter does not affect the return value. If page + streaming is performed per-page, this determines the maximum number + of resources in a page. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -412,7 +547,10 @@ def create_finding( that is provided to the method. Returns: - A :class:`~google.cloud.securitycenter_v1.types.Finding` instance. + A :class:`~google.api_core.page_iterator.PageIterator` instance. + An iterable of :class:`~google.cloud.securitycenter_v1.types.GroupResult` instances. + You can also iterate over the pages of the response + using its `pages` property. Raises: google.api_core.exceptions.GoogleAPICallError: If the request @@ -422,18 +560,23 @@ def create_finding( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "create_finding" not in self._inner_api_calls: + if "group_assets" not in self._inner_api_calls: self._inner_api_calls[ - "create_finding" + "group_assets" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_finding, - default_retry=self._method_configs["CreateFinding"].retry, - default_timeout=self._method_configs["CreateFinding"].timeout, + self.transport.group_assets, + default_retry=self._method_configs["GroupAssets"].retry, + default_timeout=self._method_configs["GroupAssets"].timeout, client_info=self._client_info, ) - request = securitycenter_service_pb2.CreateFindingRequest( - parent=parent, finding_id=finding_id, finding=finding, + request = securitycenter_service_pb2.GroupAssetsRequest( + parent=parent, + group_by=group_by, + filter=filter_, + compare_duration=compare_duration, + read_time=read_time, + page_size=page_size, ) if metadata is None: metadata = [] @@ -448,50 +591,187 @@ def create_finding( ) metadata.append(routing_metadata) - return self._inner_api_calls["create_finding"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - - def create_notification_config( - self, - parent, - config_id, - notification_config, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, + iterator = google.api_core.page_iterator.GRPCIterator( + client=None, + method=functools.partial( + self._inner_api_calls["group_assets"], + retry=retry, + timeout=timeout, + metadata=metadata, + ), + request=request, + items_field="group_by_results", + request_token_field="page_token", + response_token_field="next_page_token", + ) + return iterator + + def group_findings( + self, + parent, + group_by, + filter_=None, + read_time=None, + compare_duration=None, + page_size=None, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ - Creates a notification config. + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. Example: + /v1/organizations/{organization_id}/sources/-/findings Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> - >>> parent = client.organization_path('[ORGANIZATION]') + >>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]') >>> - >>> # TODO: Initialize `config_id`: - >>> config_id = '' + >>> # TODO: Initialize `group_by`: + >>> group_by = '' >>> - >>> # TODO: Initialize `notification_config`: - >>> notification_config = {} + >>> # Iterate over all results + >>> for element in client.group_findings(parent, group_by): + ... # process element + ... pass >>> - >>> response = client.create_notification_config(parent, config_id, notification_config) + >>> + >>> # Alternatively: + >>> + >>> # Iterate over results one page at a time + >>> for page in client.group_findings(parent, group_by).pages: + ... for element in page: + ... # process element + ... pass Args: - parent (str): Required. Resource name of the new notification config's parent. Its - format is "organizations/[organization_id]". - config_id (str): Required. - Unique identifier provided by the client within the parent scope. - It must be between 1 and 128 characters, and contains alphanumeric - characters, underscores or hyphens only. - notification_config (Union[dict, ~google.cloud.securitycenter_v1.types.NotificationConfig]): Required. The notification config being created. The name and the service - account will be ignored as they are both output only fields on this - resource. + parent (str): Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]". To groupBy across + all sources provide a source_id of ``-``. For example: + organizations/{organization_id}/sources/- + group_by (str): Required. Expression that defines what assets fields to use for + grouping (including ``state_change``). The string value should follow + SQL syntax: comma separated list of fields. For example: + "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + + The following fields are supported when compare_duration is set: + + - state_change + filter_ (str): Expression that defines the filter to apply across findings. The + expression is a list of one or more restrictions combined via logical + operators ``AND`` and ``OR``. Parentheses are supported, and ``OR`` has + higher precedence than ``AND``. + + Restrictions have the form `` `` and may have a + ``-`` character in front of them to indicate negation. Examples include: + + - name + - source_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - parent: ``=``, ``:`` + + - resource_name: ``=``, ``:`` + + - state: ``=``, ``:`` + + - category: ``=``, ``:`` + + - external_uri: ``=``, ``:`` + + - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an RFC3339 string. + Examples: ``event_time = "2019-06-10T16:07:18-07:00"`` + ``event_time = 1560208038000`` + + - security_marks.marks: ``=``, ``:`` + + - source_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, ``<=`` + + For example, ``source_properties.size = 100`` is a valid filter string. + + Use a partial match on the empty string to filter based on a property + existing: ``source_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter based on a + property not existing: ``-source_properties.my_property : ""`` + read_time (Union[dict, ~google.cloud.securitycenter_v1.types.Timestamp]): Time used as a reference point when filtering findings. The filter is + limited to findings existing at the supplied time and their values are + those at that specific time. Absence of this field will default to the + API's version of NOW. If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.NotificationConfig` + message :class:`~google.cloud.securitycenter_v1.types.Timestamp` + compare_duration (Union[dict, ~google.cloud.securitycenter_v1.types.Duration]): When compare_duration is set, the GroupResult's "state_change" + attribute is updated to indicate whether the finding had its state + changed, the finding's state remained unchanged, or if the finding was + added during the compare_duration period of time that precedes the + read_time. This is the time between (read_time - compare_duration) and + read_time. + + The state_change value is derived based on the presence and state of the + finding at the two points in time. Intermediate state changes between + the two times don't affect the result. For example, the results aren't + affected if the finding is made inactive and then active again. + + Possible "state_change" values when compare_duration is specified: + + - "CHANGED": indicates that the finding was present and matched the + given filter at the start of compare_duration, but changed its state + at read_time. + - "UNCHANGED": indicates that the finding was present and matched the + given filter at the start of compare_duration and did not change + state at read_time. + - "ADDED": indicates that the finding did not match the given filter or + was not present at the start of compare_duration, but was present at + read_time. + - "REMOVED": indicates that the finding was present and matched the + filter at the start of compare_duration, but did not match the filter + at read_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set for all + findings present at read_time. + + If this field is set then ``state_change`` must be a specified field in + ``group_by``. + + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.securitycenter_v1.types.Duration` + page_size (int): The maximum number of resources contained in the + underlying API response. If page streaming is performed per- + resource, this parameter does not affect the return value. If page + streaming is performed per-page, this determines the maximum number + of resources in a page. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -502,7 +782,10 @@ def create_notification_config( that is provided to the method. Returns: - A :class:`~google.cloud.securitycenter_v1.types.NotificationConfig` instance. + A :class:`~google.api_core.page_iterator.PageIterator` instance. + An iterable of :class:`~google.cloud.securitycenter_v1.types.GroupResult` instances. + You can also iterate over the pages of the response + using its `pages` property. Raises: google.api_core.exceptions.GoogleAPICallError: If the request @@ -512,20 +795,23 @@ def create_notification_config( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "create_notification_config" not in self._inner_api_calls: + if "group_findings" not in self._inner_api_calls: self._inner_api_calls[ - "create_notification_config" + "group_findings" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_notification_config, - default_retry=self._method_configs["CreateNotificationConfig"].retry, - default_timeout=self._method_configs[ - "CreateNotificationConfig" - ].timeout, + self.transport.group_findings, + default_retry=self._method_configs["GroupFindings"].retry, + default_timeout=self._method_configs["GroupFindings"].timeout, client_info=self._client_info, ) - request = securitycenter_service_pb2.CreateNotificationConfigRequest( - parent=parent, config_id=config_id, notification_config=notification_config, + request = securitycenter_service_pb2.GroupFindingsRequest( + parent=parent, + group_by=group_by, + filter=filter_, + read_time=read_time, + compare_duration=compare_duration, + page_size=page_size, ) if metadata is None: metadata = [] @@ -540,32 +826,52 @@ def create_notification_config( ) metadata.append(routing_metadata) - return self._inner_api_calls["create_notification_config"]( - request, retry=retry, timeout=timeout, metadata=metadata + iterator = google.api_core.page_iterator.GRPCIterator( + client=None, + method=functools.partial( + self._inner_api_calls["group_findings"], + retry=retry, + timeout=timeout, + metadata=metadata, + ), + request=request, + items_field="group_by_results", + request_token_field="page_token", + response_token_field="next_page_token", ) + return iterator - def delete_notification_config( + def test_iam_permissions( self, - name, + resource, + permissions, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ - Deletes a notification config. + Returns the permissions that a caller has on the specified source. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> - >>> name = client.notification_config_path('[ORGANIZATION]', '[NOTIFICATION_CONFIG]') + >>> # TODO: Initialize `resource`: + >>> resource = '' >>> - >>> client.delete_notification_config(name) + >>> # TODO: Initialize `permissions`: + >>> permissions = [] + >>> + >>> response = client.test_iam_permissions(resource, permissions) Args: - name (str): Required. Name of the notification config to delete. Its format is - "organizations/[organization_id]/notificationConfigs/[config_id]". + resource (str): REQUIRED: The resource for which the policy detail is being requested. + See the operation documentation for the appropriate value for this field. + permissions (list[str]): The set of permissions to check for the ``resource``. Permissions + with wildcards (such as '*' or 'storage.*') are not allowed. For more + information see `IAM + Overview `__. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -575,6 +881,9 @@ def delete_notification_config( metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. + Returns: + A :class:`~google.cloud.securitycenter_v1.types.TestIamPermissionsResponse` instance. + Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. @@ -583,24 +892,24 @@ def delete_notification_config( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "delete_notification_config" not in self._inner_api_calls: + if "test_iam_permissions" not in self._inner_api_calls: self._inner_api_calls[ - "delete_notification_config" + "test_iam_permissions" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.delete_notification_config, - default_retry=self._method_configs["DeleteNotificationConfig"].retry, - default_timeout=self._method_configs[ - "DeleteNotificationConfig" - ].timeout, + self.transport.test_iam_permissions, + default_retry=self._method_configs["TestIamPermissions"].retry, + default_timeout=self._method_configs["TestIamPermissions"].timeout, client_info=self._client_info, ) - request = securitycenter_service_pb2.DeleteNotificationConfigRequest(name=name,) + request = iam_policy_pb2.TestIamPermissionsRequest( + resource=resource, permissions=permissions, + ) if metadata is None: metadata = [] metadata = list(metadata) try: - routing_header = [("name", name)] + routing_header = [("resource", resource)] except AttributeError: pass else: @@ -609,39 +918,41 @@ def delete_notification_config( ) metadata.append(routing_metadata) - self._inner_api_calls["delete_notification_config"]( + return self._inner_api_calls["test_iam_permissions"]( request, retry=retry, timeout=timeout, metadata=metadata ) - def get_iam_policy( + def create_source( self, - resource, - options_=None, + parent, + source, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ - Gets the access control policy on the specified Source. + Creates a source. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> - >>> # TODO: Initialize `resource`: - >>> resource = '' + >>> parent = client.organization_path('[ORGANIZATION]') >>> - >>> response = client.get_iam_policy(resource) + >>> # TODO: Initialize `source`: + >>> source = {} + >>> + >>> response = client.create_source(parent, source) Args: - resource (str): REQUIRED: The resource for which the policy is being requested. - See the operation documentation for the appropriate value for this field. - options_ (Union[dict, ~google.cloud.securitycenter_v1.types.GetPolicyOptions]): OPTIONAL: A ``GetPolicyOptions`` object for specifying options to - ``GetIamPolicy``. This field is only used by Cloud IAM. + parent (str): Required. Resource name of the new source's parent. Its format + should be "organizations/[organization_id]". + source (Union[dict, ~google.cloud.securitycenter_v1.types.Source]): Required. The Source being created, only the display_name and + description will be used. All other fields will be ignored. If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.GetPolicyOptions` + message :class:`~google.cloud.securitycenter_v1.types.Source` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -652,7 +963,7 @@ def get_iam_policy( that is provided to the method. Returns: - A :class:`~google.cloud.securitycenter_v1.types.Policy` instance. + A :class:`~google.cloud.securitycenter_v1.types.Source` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request @@ -662,24 +973,24 @@ def get_iam_policy( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "get_iam_policy" not in self._inner_api_calls: + if "create_source" not in self._inner_api_calls: self._inner_api_calls[ - "get_iam_policy" + "create_source" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_iam_policy, - default_retry=self._method_configs["GetIamPolicy"].retry, - default_timeout=self._method_configs["GetIamPolicy"].timeout, + self.transport.create_source, + default_retry=self._method_configs["CreateSource"].retry, + default_timeout=self._method_configs["CreateSource"].timeout, client_info=self._client_info, ) - request = iam_policy_pb2.GetIamPolicyRequest( - resource=resource, options=options_, + request = securitycenter_service_pb2.CreateSourceRequest( + parent=parent, source=source, ) if metadata is None: metadata = [] metadata = list(metadata) try: - routing_header = [("resource", resource)] + routing_header = [("parent", parent)] except AttributeError: pass else: @@ -688,32 +999,49 @@ def get_iam_policy( ) metadata.append(routing_metadata) - return self._inner_api_calls["get_iam_policy"]( + return self._inner_api_calls["create_source"]( request, retry=retry, timeout=timeout, metadata=metadata ) - def get_notification_config( + def create_finding( self, - name, + parent, + finding_id, + finding, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ - Gets a notification config. + Creates a finding. The corresponding source must exist for finding creation + to succeed. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> - >>> name = client.notification_config_path('[ORGANIZATION]', '[NOTIFICATION_CONFIG]') + >>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]') >>> - >>> response = client.get_notification_config(name) + >>> # TODO: Initialize `finding_id`: + >>> finding_id = '' + >>> + >>> # TODO: Initialize `finding`: + >>> finding = {} + >>> + >>> response = client.create_finding(parent, finding_id, finding) Args: - name (str): Required. Name of the notification config to get. Its format is - "organizations/[organization_id]/notificationConfigs/[config_id]". + parent (str): Required. Resource name of the new finding's parent. Its format + should be "organizations/[organization_id]/sources/[source_id]". + finding_id (str): Required. Unique identifier provided by the client within the parent scope. + It must be alphanumeric and less than or equal to 32 characters and + greater than 0 characters in length. + finding (Union[dict, ~google.cloud.securitycenter_v1.types.Finding]): Required. The Finding being created. The name and security_marks + will be ignored as they are both output only fields on this resource. + + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.securitycenter_v1.types.Finding` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -724,7 +1052,7 @@ def get_notification_config( that is provided to the method. Returns: - A :class:`~google.cloud.securitycenter_v1.types.NotificationConfig` instance. + A :class:`~google.cloud.securitycenter_v1.types.Finding` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request @@ -734,22 +1062,24 @@ def get_notification_config( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "get_notification_config" not in self._inner_api_calls: + if "create_finding" not in self._inner_api_calls: self._inner_api_calls[ - "get_notification_config" + "create_finding" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_notification_config, - default_retry=self._method_configs["GetNotificationConfig"].retry, - default_timeout=self._method_configs["GetNotificationConfig"].timeout, + self.transport.create_finding, + default_retry=self._method_configs["CreateFinding"].retry, + default_timeout=self._method_configs["CreateFinding"].timeout, client_info=self._client_info, ) - request = securitycenter_service_pb2.GetNotificationConfigRequest(name=name,) + request = securitycenter_service_pb2.CreateFindingRequest( + parent=parent, finding_id=finding_id, finding=finding, + ) if metadata is None: metadata = [] metadata = list(metadata) try: - routing_header = [("name", name)] + routing_header = [("parent", parent)] except AttributeError: pass else: @@ -758,32 +1088,50 @@ def get_notification_config( ) metadata.append(routing_metadata) - return self._inner_api_calls["get_notification_config"]( + return self._inner_api_calls["create_finding"]( request, retry=retry, timeout=timeout, metadata=metadata ) - def get_organization_settings( + def create_notification_config( self, - name, + parent, + config_id, + notification_config, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ - Gets the settings for an organization. + Creates a notification config. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> - >>> name = client.organization_settings_path('[ORGANIZATION]') + >>> parent = client.organization_path('[ORGANIZATION]') >>> - >>> response = client.get_organization_settings(name) + >>> # TODO: Initialize `config_id`: + >>> config_id = '' + >>> + >>> # TODO: Initialize `notification_config`: + >>> notification_config = {} + >>> + >>> response = client.create_notification_config(parent, config_id, notification_config) Args: - name (str): Required. Name of the organization to get organization settings for. - Its format is "organizations/[organization_id]/organizationSettings". + parent (str): Required. Resource name of the new notification config's parent. Its + format is "organizations/[organization_id]". + config_id (str): Required. + Unique identifier provided by the client within the parent scope. + It must be between 1 and 128 characters, and contains alphanumeric + characters, underscores or hyphens only. + notification_config (Union[dict, ~google.cloud.securitycenter_v1.types.NotificationConfig]): Required. The notification config being created. The name and the service + account will be ignored as they are both output only fields on this + resource. + + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.securitycenter_v1.types.NotificationConfig` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -794,7 +1142,7 @@ def get_organization_settings( that is provided to the method. Returns: - A :class:`~google.cloud.securitycenter_v1.types.OrganizationSettings` instance. + A :class:`~google.cloud.securitycenter_v1.types.NotificationConfig` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request @@ -804,22 +1152,26 @@ def get_organization_settings( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "get_organization_settings" not in self._inner_api_calls: + if "create_notification_config" not in self._inner_api_calls: self._inner_api_calls[ - "get_organization_settings" + "create_notification_config" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_organization_settings, - default_retry=self._method_configs["GetOrganizationSettings"].retry, - default_timeout=self._method_configs["GetOrganizationSettings"].timeout, + self.transport.create_notification_config, + default_retry=self._method_configs["CreateNotificationConfig"].retry, + default_timeout=self._method_configs[ + "CreateNotificationConfig" + ].timeout, client_info=self._client_info, ) - request = securitycenter_service_pb2.GetOrganizationSettingsRequest(name=name,) + request = securitycenter_service_pb2.CreateNotificationConfigRequest( + parent=parent, config_id=config_id, notification_config=notification_config, + ) if metadata is None: metadata = [] metadata = list(metadata) try: - routing_header = [("name", name)] + routing_header = [("parent", parent)] except AttributeError: pass else: @@ -828,11 +1180,11 @@ def get_organization_settings( ) metadata.append(routing_metadata) - return self._inner_api_calls["get_organization_settings"]( + return self._inner_api_calls["create_notification_config"]( request, retry=retry, timeout=timeout, metadata=metadata ) - def get_source( + def delete_notification_config( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, @@ -840,20 +1192,20 @@ def get_source( metadata=None, ): """ - Gets a source. + Deletes a notification config. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> - >>> name = client.source_path('[ORGANIZATION]', '[SOURCE]') + >>> name = client.notification_config_path('[ORGANIZATION]', '[NOTIFICATION_CONFIG]') >>> - >>> response = client.get_source(name) + >>> client.delete_notification_config(name) Args: - name (str): Required. Relative resource name of the source. Its format is - "organizations/[organization_id]/source/[source_id]". + name (str): Required. Name of the notification config to delete. Its format is + "organizations/[organization_id]/notificationConfigs/[config_id]". retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -863,9 +1215,6 @@ def get_source( metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. - Returns: - A :class:`~google.cloud.securitycenter_v1.types.Source` instance. - Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. @@ -874,17 +1223,19 @@ def get_source( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "get_source" not in self._inner_api_calls: + if "delete_notification_config" not in self._inner_api_calls: self._inner_api_calls[ - "get_source" + "delete_notification_config" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_source, - default_retry=self._method_configs["GetSource"].retry, - default_timeout=self._method_configs["GetSource"].timeout, + self.transport.delete_notification_config, + default_retry=self._method_configs["DeleteNotificationConfig"].retry, + default_timeout=self._method_configs[ + "DeleteNotificationConfig" + ].timeout, client_info=self._client_info, ) - request = securitycenter_service_pb2.GetSourceRequest(name=name,) + request = securitycenter_service_pb2.DeleteNotificationConfigRequest(name=name,) if metadata is None: metadata = [] metadata = list(metadata) @@ -898,200 +1249,43 @@ def get_source( ) metadata.append(routing_metadata) - return self._inner_api_calls["get_source"]( + self._inner_api_calls["delete_notification_config"]( request, retry=retry, timeout=timeout, metadata=metadata ) - def group_assets( + def get_notification_config( self, - parent, - group_by, - filter_=None, - compare_duration=None, - read_time=None, - page_size=None, + name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ - Filters an organization's assets and groups them by their specified - properties. + Gets a notification config. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> - >>> parent = client.organization_path('[ORGANIZATION]') - >>> - >>> # TODO: Initialize `group_by`: - >>> group_by = '' - >>> - >>> # Iterate over all results - >>> for element in client.group_assets(parent, group_by): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: + >>> name = client.notification_config_path('[ORGANIZATION]', '[NOTIFICATION_CONFIG]') >>> - >>> # Iterate over results one page at a time - >>> for page in client.group_assets(parent, group_by).pages: - ... for element in page: - ... # process element - ... pass + >>> response = client.get_notification_config(name) Args: - parent (str): Required. Name of the organization to groupBy. Its format is - "organizations/[organization_id]". - group_by (str): Required. Expression that defines what assets fields to use for - grouping. The string value should follow SQL syntax: comma separated - list of fields. For example: - "security_center_properties.resource_project,security_center_properties.project". - - The following fields are supported when compare_duration is not set: - - - security_center_properties.resource_project - - security_center_properties.resource_project_display_name - - security_center_properties.resource_type - - security_center_properties.resource_parent - - security_center_properties.resource_parent_display_name + name (str): Required. Name of the notification config to get. Its format is + "organizations/[organization_id]/notificationConfigs/[config_id]". + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will + be retried using a default configuration. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata + that is provided to the method. - The following fields are supported when compare_duration is set: - - - security_center_properties.resource_type - - security_center_properties.resource_project_display_name - - security_center_properties.resource_parent_display_name - filter_ (str): Expression that defines the filter to apply across assets. The - expression is a list of zero or more restrictions combined via logical - operators ``AND`` and ``OR``. Parentheses are supported, and ``OR`` has - higher precedence than ``AND``. - - Restrictions have the form `` `` and may have a - ``-`` character in front of them to indicate negation. The fields map to - those defined in the Asset resource. Examples include: - - - name - - security_center_properties.resource_name - - resource_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an RFC3339 string. - Examples: ``update_time = "2019-06-10T16:07:18-07:00"`` - ``update_time = 1560208038000`` - - - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an RFC3339 string. - Examples: ``create_time = "2019-06-10T16:07:18-07:00"`` - ``create_time = 1560208038000`` - - - iam_policy.policy_blob: ``=``, ``:`` - - - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, ``<=`` - - - security_marks.marks: ``=``, ``:`` - - - security_center_properties.resource_name: ``=``, ``:`` - - - security_center_properties.resource_display_name: ``=``, ``:`` - - - security_center_properties.resource_type: ``=``, ``:`` - - - security_center_properties.resource_parent: ``=``, ``:`` - - - security_center_properties.resource_parent_display_name: ``=``, ``:`` - - - security_center_properties.resource_project: ``=``, ``:`` - - - security_center_properties.resource_project_display_name: ``=``, - ``:`` - - - security_center_properties.resource_owners: ``=``, ``:`` - - For example, ``resource_properties.size = 100`` is a valid filter - string. - - Use a partial match on the empty string to filter based on a property - existing:\ ``resource_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter based on a - property not existing: ``-resource_properties.my_property : ""`` - compare_duration (Union[dict, ~google.cloud.securitycenter_v1.types.Duration]): When compare_duration is set, the GroupResult's "state_change" - property is updated to indicate whether the asset was added, removed, or - remained present during the compare_duration period of time that - precedes the read_time. This is the time between (read_time - - compare_duration) and read_time. - - The state change value is derived based on the presence of the asset at - the two points in time. Intermediate state changes between the two times - don't affect the result. For example, the results aren't affected if the - asset is removed and re-created again. - - Possible "state_change" values when compare_duration is specified: - - - "ADDED": indicates that the asset was not present at the start of - compare_duration, but present at reference_time. - - "REMOVED": indicates that the asset was present at the start of - compare_duration, but not present at reference_time. - - "ACTIVE": indicates that the asset was present at both the start and - the end of the time period defined by compare_duration and - reference_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set for all - assets present at read_time. - - If this field is set then ``state_change`` must be a specified field in - ``group_by``. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Duration` - read_time (Union[dict, ~google.cloud.securitycenter_v1.types.Timestamp]): Time used as a reference point when filtering assets. The filter is limited - to assets existing at the supplied time and their values are those at that - specific time. Absence of this field will default to the API's version of - NOW. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Timestamp` - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.securitycenter_v1.types.GroupResult` instances. - You can also iterate over the pages of the response - using its `pages` property. + Returns: + A :class:`~google.cloud.securitycenter_v1.types.NotificationConfig` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request @@ -1101,218 +1295,126 @@ def group_assets( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "group_assets" not in self._inner_api_calls: + if "get_notification_config" not in self._inner_api_calls: self._inner_api_calls[ - "group_assets" + "get_notification_config" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.group_assets, - default_retry=self._method_configs["GroupAssets"].retry, - default_timeout=self._method_configs["GroupAssets"].timeout, + self.transport.get_notification_config, + default_retry=self._method_configs["GetNotificationConfig"].retry, + default_timeout=self._method_configs["GetNotificationConfig"].timeout, client_info=self._client_info, ) - request = securitycenter_service_pb2.GroupAssetsRequest( - parent=parent, - group_by=group_by, - filter=filter_, - compare_duration=compare_duration, - read_time=read_time, - page_size=page_size, - ) + request = securitycenter_service_pb2.GetNotificationConfigRequest(name=name,) if metadata is None: metadata = [] metadata = list(metadata) try: - routing_header = [("parent", parent)] + routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) - metadata.append(routing_metadata) - - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["group_assets"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="group_by_results", - request_token_field="page_token", - response_token_field="next_page_token", - ) - return iterator - - def group_findings( - self, - parent, - group_by, - filter_=None, - read_time=None, - compare_duration=None, - page_size=None, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. Example: - /v1/organizations/{organization_id}/sources/-/findings - - Example: - >>> from google.cloud import securitycenter_v1 - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]') - >>> - >>> # TODO: Initialize `group_by`: - >>> group_by = '' - >>> - >>> # Iterate over all results - >>> for element in client.group_findings(parent, group_by): - ... # process element - ... pass - >>> - >>> - >>> # Alternatively: - >>> - >>> # Iterate over results one page at a time - >>> for page in client.group_findings(parent, group_by).pages: - ... for element in page: - ... # process element - ... pass - - Args: - parent (str): Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]". To groupBy across - all sources provide a source_id of ``-``. For example: - organizations/{organization_id}/sources/- - group_by (str): Required. Expression that defines what assets fields to use for - grouping (including ``state_change``). The string value should follow - SQL syntax: comma separated list of fields. For example: - "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - - The following fields are supported when compare_duration is set: - - - state_change - filter_ (str): Expression that defines the filter to apply across findings. The - expression is a list of one or more restrictions combined via logical - operators ``AND`` and ``OR``. Parentheses are supported, and ``OR`` has - higher precedence than ``AND``. - - Restrictions have the form `` `` and may have a - ``-`` character in front of them to indicate negation. Examples include: - - - name - - source_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - parent: ``=``, ``:`` - - - resource_name: ``=``, ``:`` - - - state: ``=``, ``:`` - - - category: ``=``, ``:`` - - - external_uri: ``=``, ``:`` - - - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an RFC3339 string. - Examples: ``event_time = "2019-06-10T16:07:18-07:00"`` - ``event_time = 1560208038000`` - - - security_marks.marks: ``=``, ``:`` + metadata.append(routing_metadata) - - source_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, ``<=`` + return self._inner_api_calls["get_notification_config"]( + request, retry=retry, timeout=timeout, metadata=metadata + ) - For example, ``source_properties.size = 100`` is a valid filter string. + def get_organization_settings( + self, + name, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT, + metadata=None, + ): + """ + Gets the settings for an organization. - Use a partial match on the empty string to filter based on a property - existing: ``source_properties.my_property : ""`` + Example: + >>> from google.cloud import securitycenter_v1 + >>> + >>> client = securitycenter_v1.SecurityCenterClient() + >>> + >>> name = client.organization_settings_path('[ORGANIZATION]') + >>> + >>> response = client.get_organization_settings(name) - Use a negated partial match on the empty string to filter based on a - property not existing: ``-source_properties.my_property : ""`` - read_time (Union[dict, ~google.cloud.securitycenter_v1.types.Timestamp]): Time used as a reference point when filtering findings. The filter is - limited to findings existing at the supplied time and their values are - those at that specific time. Absence of this field will default to the - API's version of NOW. + Args: + name (str): Required. Name of the organization to get organization settings for. + Its format is "organizations/[organization_id]/organizationSettings". + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will + be retried using a default configuration. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata + that is provided to the method. - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Timestamp` - compare_duration (Union[dict, ~google.cloud.securitycenter_v1.types.Duration]): When compare_duration is set, the GroupResult's "state_change" - attribute is updated to indicate whether the finding had its state - changed, the finding's state remained unchanged, or if the finding was - added during the compare_duration period of time that precedes the - read_time. This is the time between (read_time - compare_duration) and - read_time. + Returns: + A :class:`~google.cloud.securitycenter_v1.types.OrganizationSettings` instance. - The state_change value is derived based on the presence and state of the - finding at the two points in time. Intermediate state changes between - the two times don't affect the result. For example, the results aren't - affected if the finding is made inactive and then active again. + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + # Wrap the transport method to add retry and timeout logic. + if "get_organization_settings" not in self._inner_api_calls: + self._inner_api_calls[ + "get_organization_settings" + ] = google.api_core.gapic_v1.method.wrap_method( + self.transport.get_organization_settings, + default_retry=self._method_configs["GetOrganizationSettings"].retry, + default_timeout=self._method_configs["GetOrganizationSettings"].timeout, + client_info=self._client_info, + ) - Possible "state_change" values when compare_duration is specified: + request = securitycenter_service_pb2.GetOrganizationSettingsRequest(name=name,) + if metadata is None: + metadata = [] + metadata = list(metadata) + try: + routing_header = [("name", name)] + except AttributeError: + pass + else: + routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( + routing_header + ) + metadata.append(routing_metadata) - - "CHANGED": indicates that the finding was present and matched the - given filter at the start of compare_duration, but changed its state - at read_time. - - "UNCHANGED": indicates that the finding was present and matched the - given filter at the start of compare_duration and did not change - state at read_time. - - "ADDED": indicates that the finding did not match the given filter or - was not present at the start of compare_duration, but was present at - read_time. - - "REMOVED": indicates that the finding was present and matched the - filter at the start of compare_duration, but did not match the filter - at read_time. + return self._inner_api_calls["get_organization_settings"]( + request, retry=retry, timeout=timeout, metadata=metadata + ) - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set for all - findings present at read_time. + def get_source( + self, + name, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT, + metadata=None, + ): + """ + Gets a source. - If this field is set then ``state_change`` must be a specified field in - ``group_by``. + Example: + >>> from google.cloud import securitycenter_v1 + >>> + >>> client = securitycenter_v1.SecurityCenterClient() + >>> + >>> name = client.source_path('[ORGANIZATION]', '[SOURCE]') + >>> + >>> response = client.get_source(name) - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Duration` - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. + Args: + name (str): Required. Relative resource name of the source. Its format is + "organizations/[organization_id]/source/[source_id]". retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -1323,10 +1425,7 @@ def group_findings( that is provided to the method. Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.securitycenter_v1.types.GroupResult` instances. - You can also iterate over the pages of the response - using its `pages` property. + A :class:`~google.cloud.securitycenter_v1.types.Source` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request @@ -1336,29 +1435,22 @@ def group_findings( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "group_findings" not in self._inner_api_calls: + if "get_source" not in self._inner_api_calls: self._inner_api_calls[ - "group_findings" + "get_source" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.group_findings, - default_retry=self._method_configs["GroupFindings"].retry, - default_timeout=self._method_configs["GroupFindings"].timeout, + self.transport.get_source, + default_retry=self._method_configs["GetSource"].retry, + default_timeout=self._method_configs["GetSource"].timeout, client_info=self._client_info, ) - request = securitycenter_service_pb2.GroupFindingsRequest( - parent=parent, - group_by=group_by, - filter=filter_, - read_time=read_time, - compare_duration=compare_duration, - page_size=page_size, - ) + request = securitycenter_service_pb2.GetSourceRequest(name=name,) if metadata is None: metadata = [] metadata = list(metadata) try: - routing_header = [("parent", parent)] + routing_header = [("name", name)] except AttributeError: pass else: @@ -1367,20 +1459,9 @@ def group_findings( ) metadata.append(routing_metadata) - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["group_findings"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="group_by_results", - request_token_field="page_token", - response_token_field="next_page_token", + return self._inner_api_calls["get_source"]( + request, retry=retry, timeout=timeout, metadata=metadata ) - return iterator def list_assets( self, @@ -2313,87 +2394,6 @@ def set_iam_policy( request, retry=retry, timeout=timeout, metadata=metadata ) - def test_iam_permissions( - self, - resource, - permissions, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Returns the permissions that a caller has on the specified source. - - Example: - >>> from google.cloud import securitycenter_v1 - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> # TODO: Initialize `resource`: - >>> resource = '' - >>> - >>> # TODO: Initialize `permissions`: - >>> permissions = [] - >>> - >>> response = client.test_iam_permissions(resource, permissions) - - Args: - resource (str): REQUIRED: The resource for which the policy detail is being requested. - See the operation documentation for the appropriate value for this field. - permissions (list[str]): The set of permissions to check for the ``resource``. Permissions - with wildcards (such as '*' or 'storage.*') are not allowed. For more - information see `IAM - Overview `__. - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. - - Returns: - A :class:`~google.cloud.securitycenter_v1.types.TestIamPermissionsResponse` instance. - - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "test_iam_permissions" not in self._inner_api_calls: - self._inner_api_calls[ - "test_iam_permissions" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.test_iam_permissions, - default_retry=self._method_configs["TestIamPermissions"].retry, - default_timeout=self._method_configs["TestIamPermissions"].timeout, - client_info=self._client_info, - ) - - request = iam_policy_pb2.TestIamPermissionsRequest( - resource=resource, permissions=permissions, - ) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("resource", resource)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) - - return self._inner_api_calls["test_iam_permissions"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) - def update_finding( self, finding, diff --git a/google/cloud/securitycenter_v1/gapic/security_center_client_config.py b/google/cloud/securitycenter_v1/gapic/security_center_client_config.py index 111431ea..7bf5a897 100644 --- a/google/cloud/securitycenter_v1/gapic/security_center_client_config.py +++ b/google/cloud/securitycenter_v1/gapic/security_center_client_config.py @@ -2,174 +2,135 @@ "interfaces": { "google.cloud.securitycenter.v1.SecurityCenter": { "retry_codes": { - "retry_policy_1_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "no_retry_2_codes": [], - "no_retry_codes": [], - "retry_policy_2_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "no_retry_1_codes": [], + "idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], + "non_idempotent": [], }, "retry_params": { - "retry_policy_1_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 60000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 60000, - }, - "retry_policy_2_params": { + "default": { "initial_retry_delay_millis": 100, "retry_delay_multiplier": 1.3, "max_retry_delay_millis": 60000, "initial_rpc_timeout_millis": 480000, "rpc_timeout_multiplier": 1.0, "max_rpc_timeout_millis": 480000, - "total_timeout_millis": 480000, + "total_timeout_millis": 600000, + } + }, + "methods": { + "GetIamPolicy": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default", }, - "no_retry_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 0, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 0, - "total_timeout_millis": 0, - }, - "no_retry_1_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 60000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 60000, + "GroupAssets": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default", }, - "no_retry_2_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 480000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 480000, - "total_timeout_millis": 480000, + "GroupFindings": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default", + }, + "TestIamPermissions": { + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default", }, - }, - "methods": { "CreateSource": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "CreateFinding": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "CreateNotificationConfig": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "DeleteNotificationConfig": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "GetIamPolicy": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "GetNotificationConfig": { "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", + "retry_codes_name": "idempotent", + "retry_params_name": "default", }, "GetOrganizationSettings": { "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", + "retry_codes_name": "idempotent", + "retry_params_name": "default", }, "GetSource": { "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", - }, - "GroupAssets": { - "timeout_millis": 480000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", - }, - "GroupFindings": { - "timeout_millis": 480000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", + "retry_codes_name": "idempotent", + "retry_params_name": "default", }, "ListAssets": { - "timeout_millis": 480000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default", }, "ListFindings": { - "timeout_millis": 480000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default", }, "ListNotificationConfigs": { "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", + "retry_codes_name": "idempotent", + "retry_params_name": "default", }, "ListSources": { "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", + "retry_codes_name": "idempotent", + "retry_params_name": "default", }, "RunAssetDiscovery": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "SetFindingState": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "SetIamPolicy": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", - }, - "TestIamPermissions": { - "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "UpdateFinding": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "UpdateNotificationConfig": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "UpdateOrganizationSettings": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "UpdateSource": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "UpdateSecurityMarks": { - "timeout_millis": 480000, - "retry_codes_name": "no_retry_2_codes", - "retry_params_name": "no_retry_2_params", + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, }, } diff --git a/google/cloud/securitycenter_v1/gapic/transports/security_center_grpc_transport.py b/google/cloud/securitycenter_v1/gapic/transports/security_center_grpc_transport.py index 58249a17..1d16b3f2 100644 --- a/google/cloud/securitycenter_v1/gapic/transports/security_center_grpc_transport.py +++ b/google/cloud/securitycenter_v1/gapic/transports/security_center_grpc_transport.py @@ -120,6 +120,63 @@ def channel(self): """ return self._channel + @property + def get_iam_policy(self): + """Return the gRPC stub for :meth:`SecurityCenterClient.get_iam_policy`. + + Gets the access control policy on the specified Source. + + Returns: + Callable: A callable which accepts the appropriate + deserialized request object and returns a + deserialized response object. + """ + return self._stubs["security_center_stub"].GetIamPolicy + + @property + def group_assets(self): + """Return the gRPC stub for :meth:`SecurityCenterClient.group_assets`. + + Filters an organization's assets and groups them by their specified + properties. + + Returns: + Callable: A callable which accepts the appropriate + deserialized request object and returns a + deserialized response object. + """ + return self._stubs["security_center_stub"].GroupAssets + + @property + def group_findings(self): + """Return the gRPC stub for :meth:`SecurityCenterClient.group_findings`. + + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. Example: + /v1/organizations/{organization_id}/sources/-/findings + + Returns: + Callable: A callable which accepts the appropriate + deserialized request object and returns a + deserialized response object. + """ + return self._stubs["security_center_stub"].GroupFindings + + @property + def test_iam_permissions(self): + """Return the gRPC stub for :meth:`SecurityCenterClient.test_iam_permissions`. + + Returns the permissions that a caller has on the specified source. + + Returns: + Callable: A callable which accepts the appropriate + deserialized request object and returns a + deserialized response object. + """ + return self._stubs["security_center_stub"].TestIamPermissions + @property def create_source(self): """Return the gRPC stub for :meth:`SecurityCenterClient.create_source`. @@ -173,19 +230,6 @@ def delete_notification_config(self): """ return self._stubs["security_center_stub"].DeleteNotificationConfig - @property - def get_iam_policy(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.get_iam_policy`. - - Gets the access control policy on the specified Source. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].GetIamPolicy - @property def get_notification_config(self): """Return the gRPC stub for :meth:`SecurityCenterClient.get_notification_config`. @@ -225,37 +269,6 @@ def get_source(self): """ return self._stubs["security_center_stub"].GetSource - @property - def group_assets(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.group_assets`. - - Filters an organization's assets and groups them by their specified - properties. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].GroupAssets - - @property - def group_findings(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.group_findings`. - - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. Example: - /v1/organizations/{organization_id}/sources/-/findings - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].GroupFindings - @property def list_assets(self): """Return the gRPC stub for :meth:`SecurityCenterClient.list_assets`. @@ -355,19 +368,6 @@ def set_iam_policy(self): """ return self._stubs["security_center_stub"].SetIamPolicy - @property - def test_iam_permissions(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.test_iam_permissions`. - - Returns the permissions that a caller has on the specified source. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].TestIamPermissions - @property def update_finding(self): """Return the gRPC stub for :meth:`SecurityCenterClient.update_finding`. diff --git a/google/cloud/securitycenter_v1/py.typed b/google/cloud/securitycenter_v1/py.typed new file mode 100644 index 00000000..23a44fc7 --- /dev/null +++ b/google/cloud/securitycenter_v1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-securitycenter package uses inline types. diff --git a/google/cloud/securitycenter_v1/services/__init__.py b/google/cloud/securitycenter_v1/services/__init__.py new file mode 100644 index 00000000..42ffdf2b --- /dev/null +++ b/google/cloud/securitycenter_v1/services/__init__.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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. +# diff --git a/google/cloud/securitycenter_v1/services/security_center/__init__.py b/google/cloud/securitycenter_v1/services/security_center/__init__.py new file mode 100644 index 00000000..6250349b --- /dev/null +++ b/google/cloud/securitycenter_v1/services/security_center/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 SecurityCenterClient +from .async_client import SecurityCenterAsyncClient + +__all__ = ( + "SecurityCenterClient", + "SecurityCenterAsyncClient", +) diff --git a/google/cloud/securitycenter_v1/services/security_center/async_client.py b/google/cloud/securitycenter_v1/services/security_center/async_client.py new file mode 100644 index 00000000..ea5a73ae --- /dev/null +++ b/google/cloud/securitycenter_v1/services/security_center/async_client.py @@ -0,0 +1,2226 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation +from google.api_core import operation_async +from google.cloud.securitycenter_v1.services.security_center import pagers +from google.cloud.securitycenter_v1.types import finding +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import ( + notification_config as gcs_notification_config, +) +from google.cloud.securitycenter_v1.types import organization_settings +from google.cloud.securitycenter_v1.types import ( + organization_settings as gcs_organization_settings, +) +from google.cloud.securitycenter_v1.types import run_asset_discovery_response +from google.cloud.securitycenter_v1.types import security_marks +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import source +from google.cloud.securitycenter_v1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + +from .transports.base import SecurityCenterTransport +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .client import SecurityCenterClient + + +class SecurityCenterAsyncClient: + """V1 APIs for Security Center service.""" + + _client: SecurityCenterClient + + DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + + notification_config_path = staticmethod( + SecurityCenterClient.notification_config_path + ) + + source_path = staticmethod(SecurityCenterClient.source_path) + + security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + + organization_settings_path = staticmethod( + SecurityCenterClient.organization_settings_path + ) + + finding_path = staticmethod(SecurityCenterClient.finding_path) + + from_service_account_file = SecurityCenterClient.from_service_account_file + from_service_account_json = from_service_account_file + + get_transport_class = functools.partial( + type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, SecurityCenterTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + ) -> None: + """Instantiate the security center 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. + transport (Union[str, ~.SecurityCenterTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = SecurityCenterClient( + credentials=credentials, transport=transport, client_options=client_options, + ) + + async def create_source( + self, + request: securitycenter_service.CreateSourceRequest = None, + *, + parent: str = None, + source: gcs_source.Source = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a source. + + Args: + request (:class:`~.securitycenter_service.CreateSourceRequest`): + The request object. Request message for creating a + source. + parent (:class:`str`): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (:class:`~.gcs_source.Source`): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + This corresponds to the ``source`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, source]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.CreateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_source, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def create_finding( + self, + request: securitycenter_service.CreateFindingRequest = None, + *, + parent: str = None, + finding_id: str = None, + finding: gcs_finding.Finding = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Args: + request (:class:`~.securitycenter_service.CreateFindingRequest`): + The request object. Request message for creating a + finding. + parent (:class:`str`): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + It must be alphanumeric and less than or + equal to 32 characters and greater than + 0 characters in length. + This corresponds to the ``finding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (:class:`~.gcs_finding.Finding`): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + This corresponds to the ``finding`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_finding.Finding: + Security Command Center finding. + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, finding_id, finding]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.CreateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if finding_id is not None: + request.finding_id = finding_id + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_finding, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def create_notification_config( + self, + request: securitycenter_service.CreateNotificationConfigRequest = None, + *, + parent: str = None, + config_id: str = None, + notification_config: gcs_notification_config.NotificationConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Creates a notification config. + + Args: + request (:class:`~.securitycenter_service.CreateNotificationConfigRequest`): + The request object. Request message for creating a + notification config. + parent (:class:`str`): + Required. Resource name of the new notification config's + parent. Its format is "organizations/[organization_id]". + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config_id (:class:`str`): + Required. + Unique identifier provided by the client + within the parent scope. It must be + between 1 and 128 characters, and + contains alphanumeric characters, + underscores or hyphens only. + This corresponds to the ``config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notification_config (:class:`~.gcs_notification_config.NotificationConfig`): + Required. The notification config + being created. The name and the service + account will be ignored as they are both + output only fields on this resource. + This corresponds to the ``notification_config`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_notification_config.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, config_id, notification_config]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.CreateNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if config_id is not None: + request.config_id = config_id + if notification_config is not None: + request.notification_config = notification_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_notification_config, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_notification_config( + self, + request: securitycenter_service.DeleteNotificationConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a notification config. + + Args: + request (:class:`~.securitycenter_service.DeleteNotificationConfigRequest`): + The request object. Request message for deleting a + notification config. + name (:class:`str`): + Required. Name of the notification config to delete. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_id]". + This corresponds to the ``name`` 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.DeleteNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_notification_config, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def get_iam_policy( + self, + request: iam_policy.GetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Gets the access control policy on the specified + Source. + + Args: + request (:class:`~.iam_policy.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + This corresponds to the ``resource`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([resource]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.GetIamPolicyRequest(**request) + + elif not request: + request = iam_policy.GetIamPolicyRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_notification_config( + self, + request: securitycenter_service.GetNotificationConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> notification_config.NotificationConfig: + r"""Gets a notification config. + + Args: + request (:class:`~.securitycenter_service.GetNotificationConfigRequest`): + The request object. Request message for getting a + notification config. + name (:class:`str`): + Required. Name of the notification config to get. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_id]". + This corresponds to the ``name`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.notification_config.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.GetNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_notification_config, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_organization_settings( + self, + request: securitycenter_service.GetOrganizationSettingsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> organization_settings.OrganizationSettings: + r"""Gets the settings for an organization. + + Args: + request (:class:`~.securitycenter_service.GetOrganizationSettingsRequest`): + The request object. Request message for getting + organization settings. + name (:class:`str`): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + This corresponds to the ``name`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.organization_settings.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.GetOrganizationSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_organization_settings, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_source( + self, + request: securitycenter_service.GetSourceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Gets a source. + + Args: + request (:class:`~.securitycenter_service.GetSourceRequest`): + The request object. Request message for getting a + source. + name (:class:`str`): + Required. Relative resource name of the source. Its + format is + "organizations/[organization_id]/source/[source_id]". + This corresponds to the ``name`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.GetSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_source, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def group_assets( + self, + request: securitycenter_service.GroupAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupAssetsAsyncPager: + r"""Filters an organization's assets and groups them by + their specified properties. + + Args: + request (:class:`~.securitycenter_service.GroupAssetsRequest`): + The request object. Request message for grouping by + assets. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.GroupAssetsAsyncPager: + Response message for grouping by + assets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + + request = securitycenter_service.GroupAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.group_assets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.GroupAssetsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def group_findings( + self, + request: securitycenter_service.GroupFindingsRequest = None, + *, + parent: str = None, + group_by: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsAsyncPager: + r"""Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings + + Args: + request (:class:`~.securitycenter_service.GroupFindingsRequest`): + The request object. Request message for grouping by + findings. + parent (:class:`str`): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]". + To groupBy across all sources provide a source_id of + ``-``. For example: + organizations/{organization_id}/sources/- + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (:class:`str`): + Required. Expression that defines what assets fields to + use for grouping (including ``state_change``). The + string value should follow SQL syntax: comma separated + list of fields. For example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + + The following fields are supported when compare_duration + is set: + + - state_change + This corresponds to the ``group_by`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.GroupFindingsAsyncPager: + Response message for group by + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, group_by]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.GroupFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.group_findings, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.GroupFindingsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_assets( + self, + request: securitycenter_service.ListAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsAsyncPager: + r"""Lists an organization's assets. + + Args: + request (:class:`~.securitycenter_service.ListAssetsRequest`): + The request object. Request message for listing assets. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListAssetsAsyncPager: + Response message for listing assets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + + request = securitycenter_service.ListAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_assets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAssetsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_findings( + self, + request: securitycenter_service.ListFindingsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFindingsAsyncPager: + r"""Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings + + Args: + request (:class:`~.securitycenter_service.ListFindingsRequest`): + The request object. Request message for listing + findings. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListFindingsAsyncPager: + Response message for listing + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + + request = securitycenter_service.ListFindingsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_findings, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListFindingsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_notification_configs( + self, + request: securitycenter_service.ListNotificationConfigsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListNotificationConfigsAsyncPager: + r"""Lists notification configs. + + Args: + request (:class:`~.securitycenter_service.ListNotificationConfigsRequest`): + The request object. Request message for listing + notification configs. + parent (:class:`str`): + Required. Name of the organization to list notification + configs. Its format is + "organizations/[organization_id]". + This corresponds to the ``parent`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListNotificationConfigsAsyncPager: + Response message for listing + notification configs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.ListNotificationConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_notification_configs, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListNotificationConfigsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_sources( + self, + request: securitycenter_service.ListSourcesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSourcesAsyncPager: + r"""Lists all sources belonging to an organization. + + Args: + request (:class:`~.securitycenter_service.ListSourcesRequest`): + The request object. Request message for listing sources. + parent (:class:`str`): + Required. Resource name of the parent of sources to + list. Its format should be + "organizations/[organization_id]". + This corresponds to the ``parent`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListSourcesAsyncPager: + Response message for listing sources. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.ListSourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_sources, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSourcesAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def run_asset_discovery( + self, + request: securitycenter_service.RunAssetDiscoveryRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Args: + request (:class:`~.securitycenter_service.RunAssetDiscoveryRequest`): + The request object. Request message for running asset + discovery for an organization. + parent (:class:`str`): + Required. Name of the organization to run asset + discovery for. Its format is + "organizations/[organization_id]". + This corresponds to the ``parent`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.run_asset_discovery_response.RunAssetDiscoveryResponse``: + Response of asset discovery run + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.RunAssetDiscoveryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.run_asset_discovery, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + run_asset_discovery_response.RunAssetDiscoveryResponse, + metadata_type=empty.Empty, + ) + + # Done; return the response. + return response + + async def set_finding_state( + self, + request: securitycenter_service.SetFindingStateRequest = None, + *, + name: str = None, + state: finding.Finding.State = None, + start_time: timestamp.Timestamp = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of a finding. + + Args: + request (:class:`~.securitycenter_service.SetFindingStateRequest`): + The request object. Request message for updating a + finding's state. + name (:class:`str`): + Required. The relative resource name of the finding. + See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (:class:`~.finding.Finding.State`): + Required. The desired State of the + finding. + This corresponds to the ``state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + start_time (:class:`~.timestamp.Timestamp`): + Required. The time at which the + updated state takes effect. + This corresponds to the ``start_time`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.finding.Finding: + Security Command Center finding. + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name, state, start_time]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.SetFindingStateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if state is not None: + request.state = state + if start_time is not None: + request.start_time = start_time + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_finding_state, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def set_iam_policy( + self, + request: iam_policy.SetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Sets the access control policy on the specified + Source. + + Args: + request (:class:`~.iam_policy.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + This corresponds to the ``resource`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([resource]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.SetIamPolicyRequest(**request) + + elif not request: + request = iam_policy.SetIamPolicyRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: iam_policy.TestIamPermissionsRequest = None, + *, + resource: str = None, + permissions: Sequence[str] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy.TestIamPermissionsResponse: + r"""Returns the permissions that a caller has on the + specified source. + + Args: + request (:class:`~.iam_policy.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`Sequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + This corresponds to the ``permissions`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.iam_policy.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([resource, permissions]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.TestIamPermissionsRequest(**request) + + elif not request: + request = iam_policy.TestIamPermissionsRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.resource = resource + + if permissions: + request.permissions.extend(permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_finding( + self, + request: securitycenter_service.UpdateFindingRequest = None, + *, + finding: gcs_finding.Finding = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Args: + request (:class:`~.securitycenter_service.UpdateFindingRequest`): + The request object. Request message for updating or + creating a finding. + finding (:class:`~.gcs_finding.Finding`): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must be alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + This corresponds to the ``finding`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_finding.Finding: + Security Command Center finding. + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([finding]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.UpdateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_finding, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("finding.name", request.finding.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_notification_config( + self, + request: securitycenter_service.UpdateNotificationConfigRequest = None, + *, + notification_config: gcs_notification_config.NotificationConfig = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Args: + request (:class:`~.securitycenter_service.UpdateNotificationConfigRequest`): + The request object. Request message for updating a + notification config. + notification_config (:class:`~.gcs_notification_config.NotificationConfig`): + Required. The notification config to + update. + This corresponds to the ``notification_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + The FieldMask to use when updating + the notification config. + If empty all mutable fields will be + updated. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_notification_config.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([notification_config, update_mask]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.UpdateNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if notification_config is not None: + request.notification_config = notification_config + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.update_notification_config, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("notification_config.name", request.notification_config.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_organization_settings( + self, + request: securitycenter_service.UpdateOrganizationSettingsRequest = None, + *, + organization_settings: gcs_organization_settings.OrganizationSettings = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Updates an organization's settings. + + Args: + request (:class:`~.securitycenter_service.UpdateOrganizationSettingsRequest`): + The request object. Request message for updating an + organization's settings. + organization_settings (:class:`~.gcs_organization_settings.OrganizationSettings`): + Required. The organization settings + resource to update. + This corresponds to the ``organization_settings`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_organization_settings.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([organization_settings]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.UpdateOrganizationSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if organization_settings is not None: + request.organization_settings = organization_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_organization_settings, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("organization_settings.name", request.organization_settings.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_source( + self, + request: securitycenter_service.UpdateSourceRequest = None, + *, + source: gcs_source.Source = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Updates a source. + + Args: + request (:class:`~.securitycenter_service.UpdateSourceRequest`): + The request object. Request message for updating a + source. + source (:class:`~.gcs_source.Source`): + Required. The source resource to + update. + This corresponds to the ``source`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([source]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.UpdateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_source, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("source.name", request.source.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_security_marks( + self, + request: securitycenter_service.UpdateSecurityMarksRequest = None, + *, + security_marks: gcs_security_marks.SecurityMarks = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. + + Args: + request (:class:`~.securitycenter_service.UpdateSecurityMarksRequest`): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (:class:`~.gcs_security_marks.SecurityMarks`): + Required. The security marks resource + to update. + This corresponds to the ``security_marks`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_security_marks.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([security_marks]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.UpdateSecurityMarksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if security_marks is not None: + request.security_marks = security_marks + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_security_marks, + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_marks.name", request.security_marks.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-securitycenter", + ).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +__all__ = ("SecurityCenterAsyncClient",) diff --git a/google/cloud/securitycenter_v1/services/security_center/client.py b/google/cloud/securitycenter_v1/services/security_center/client.py new file mode 100644 index 00000000..c10e346c --- /dev/null +++ b/google/cloud/securitycenter_v1/services/security_center/client.py @@ -0,0 +1,2416 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 +import os +import re +from typing import Callable, Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation +from google.api_core import operation_async +from google.cloud.securitycenter_v1.services.security_center import pagers +from google.cloud.securitycenter_v1.types import finding +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import ( + notification_config as gcs_notification_config, +) +from google.cloud.securitycenter_v1.types import organization_settings +from google.cloud.securitycenter_v1.types import ( + organization_settings as gcs_organization_settings, +) +from google.cloud.securitycenter_v1.types import run_asset_discovery_response +from google.cloud.securitycenter_v1.types import security_marks +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import source +from google.cloud.securitycenter_v1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + +from .transports.base import SecurityCenterTransport +from .transports.grpc import SecurityCenterGrpcTransport +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport + + +class SecurityCenterClientMeta(type): + """Metaclass for the SecurityCenter 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[SecurityCenterTransport]] + _transport_registry["grpc"] = SecurityCenterGrpcTransport + _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[SecurityCenterTransport]: + """Return 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 SecurityCenterClient(metaclass=SecurityCenterClientMeta): + """V1 APIs for Security Center service.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert 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") + + DEFAULT_ENDPOINT = "securitycenter.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @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: + {@api.name}: 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 + + @staticmethod + def finding_path(organization: str, source: str, finding: str,) -> str: + """Return a fully-qualified finding string.""" + return "organizations/{organization}/sources/{source}/findings/{finding}".format( + organization=organization, source=source, finding=finding, + ) + + @staticmethod + def parse_finding_path(path: str) -> Dict[str, str]: + """Parse a finding path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def notification_config_path(organization: str, notification_config: str,) -> str: + """Return a fully-qualified notification_config string.""" + return "organizations/{organization}/notificationConfigs/{notification_config}".format( + organization=organization, notification_config=notification_config, + ) + + @staticmethod + def parse_notification_config_path(path: str) -> Dict[str, str]: + """Parse a notification_config path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/notificationConfigs/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def organization_settings_path(organization: str,) -> str: + """Return a fully-qualified organization_settings string.""" + return "organizations/{organization}/organizationSettings".format( + organization=organization, + ) + + @staticmethod + def parse_organization_settings_path(path: str) -> Dict[str, str]: + """Parse a organization_settings path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/organizationSettings$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def security_marks_path(organization: str, asset: str,) -> str: + """Return a fully-qualified security_marks string.""" + return "organizations/{organization}/assets/{asset}/securityMarks".format( + organization=organization, asset=asset, + ) + + @staticmethod + def parse_security_marks_path(path: str) -> Dict[str, str]: + """Parse a security_marks path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def source_path(organization: str, source: str,) -> str: + """Return a fully-qualified source string.""" + return "organizations/{organization}/sources/{source}".format( + organization=organization, source=source, + ) + + @staticmethod + def parse_source_path(path: str) -> Dict[str, str]: + """Parse a source path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/sources/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, SecurityCenterTransport] = None, + client_options: ClientOptions = None, + ) -> None: + """Instantiate the security center 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. + transport (Union[str, ~.SecurityCenterTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = ClientOptions.from_dict(client_options) + if client_options is None: + client_options = ClientOptions.ClientOptions() + + if client_options.api_endpoint is None: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") + if use_mtls_env == "never": + client_options.api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + has_client_cert_source = ( + client_options.client_cert_source is not None + or mtls.has_default_client_cert_source() + ) + client_options.api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT + if has_client_cert_source + else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SecurityCenterTransport): + # transport is a SecurityCenterTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=client_options.api_endpoint, + scopes=client_options.scopes, + api_mtls_endpoint=client_options.api_endpoint, + client_cert_source=client_options.client_cert_source, + quota_project_id=client_options.quota_project_id, + ) + + def create_source( + self, + request: securitycenter_service.CreateSourceRequest = None, + *, + parent: str = None, + source: gcs_source.Source = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a source. + + Args: + request (:class:`~.securitycenter_service.CreateSourceRequest`): + The request object. Request message for creating a + source. + parent (:class:`str`): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (:class:`~.gcs_source.Source`): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + This corresponds to the ``source`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, source]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.CreateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.create_source, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def create_finding( + self, + request: securitycenter_service.CreateFindingRequest = None, + *, + parent: str = None, + finding_id: str = None, + finding: gcs_finding.Finding = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Args: + request (:class:`~.securitycenter_service.CreateFindingRequest`): + The request object. Request message for creating a + finding. + parent (:class:`str`): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + It must be alphanumeric and less than or + equal to 32 characters and greater than + 0 characters in length. + This corresponds to the ``finding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (:class:`~.gcs_finding.Finding`): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + This corresponds to the ``finding`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_finding.Finding: + Security Command Center finding. + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, finding_id, finding]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.CreateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if finding_id is not None: + request.finding_id = finding_id + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.create_finding, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def create_notification_config( + self, + request: securitycenter_service.CreateNotificationConfigRequest = None, + *, + parent: str = None, + config_id: str = None, + notification_config: gcs_notification_config.NotificationConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Creates a notification config. + + Args: + request (:class:`~.securitycenter_service.CreateNotificationConfigRequest`): + The request object. Request message for creating a + notification config. + parent (:class:`str`): + Required. Resource name of the new notification config's + parent. Its format is "organizations/[organization_id]". + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config_id (:class:`str`): + Required. + Unique identifier provided by the client + within the parent scope. It must be + between 1 and 128 characters, and + contains alphanumeric characters, + underscores or hyphens only. + This corresponds to the ``config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notification_config (:class:`~.gcs_notification_config.NotificationConfig`): + Required. The notification config + being created. The name and the service + account will be ignored as they are both + output only fields on this resource. + This corresponds to the ``notification_config`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_notification_config.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, config_id, notification_config]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.CreateNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if config_id is not None: + request.config_id = config_id + if notification_config is not None: + request.notification_config = notification_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.create_notification_config, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_notification_config( + self, + request: securitycenter_service.DeleteNotificationConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a notification config. + + Args: + request (:class:`~.securitycenter_service.DeleteNotificationConfigRequest`): + The request object. Request message for deleting a + notification config. + name (:class:`str`): + Required. Name of the notification config to delete. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_id]". + This corresponds to the ``name`` 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.DeleteNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_notification_config, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def get_iam_policy( + self, + request: iam_policy.GetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Gets the access control policy on the specified + Source. + + Args: + request (:class:`~.iam_policy.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + This corresponds to the ``resource`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([resource]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.GetIamPolicyRequest(**request) + + elif not request: + request = iam_policy.GetIamPolicyRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_notification_config( + self, + request: securitycenter_service.GetNotificationConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> notification_config.NotificationConfig: + r"""Gets a notification config. + + Args: + request (:class:`~.securitycenter_service.GetNotificationConfigRequest`): + The request object. Request message for getting a + notification config. + name (:class:`str`): + Required. Name of the notification config to get. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_id]". + This corresponds to the ``name`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.notification_config.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.GetNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_notification_config, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_organization_settings( + self, + request: securitycenter_service.GetOrganizationSettingsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> organization_settings.OrganizationSettings: + r"""Gets the settings for an organization. + + Args: + request (:class:`~.securitycenter_service.GetOrganizationSettingsRequest`): + The request object. Request message for getting + organization settings. + name (:class:`str`): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + This corresponds to the ``name`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.organization_settings.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.GetOrganizationSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_organization_settings, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_source( + self, + request: securitycenter_service.GetSourceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Gets a source. + + Args: + request (:class:`~.securitycenter_service.GetSourceRequest`): + The request object. Request message for getting a + source. + name (:class:`str`): + Required. Relative resource name of the source. Its + format is + "organizations/[organization_id]/source/[source_id]". + This corresponds to the ``name`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.GetSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_source, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def group_assets( + self, + request: securitycenter_service.GroupAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupAssetsPager: + r"""Filters an organization's assets and groups them by + their specified properties. + + Args: + request (:class:`~.securitycenter_service.GroupAssetsRequest`): + The request object. Request message for grouping by + assets. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.GroupAssetsPager: + Response message for grouping by + assets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + + request = securitycenter_service.GroupAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.group_assets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.GroupAssetsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def group_findings( + self, + request: securitycenter_service.GroupFindingsRequest = None, + *, + parent: str = None, + group_by: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsPager: + r"""Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings + + Args: + request (:class:`~.securitycenter_service.GroupFindingsRequest`): + The request object. Request message for grouping by + findings. + parent (:class:`str`): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]". + To groupBy across all sources provide a source_id of + ``-``. For example: + organizations/{organization_id}/sources/- + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (:class:`str`): + Required. Expression that defines what assets fields to + use for grouping (including ``state_change``). The + string value should follow SQL syntax: comma separated + list of fields. For example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + + The following fields are supported when compare_duration + is set: + + - state_change + This corresponds to the ``group_by`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.GroupFindingsPager: + Response message for group by + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, group_by]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.GroupFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.group_findings, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.GroupFindingsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def list_assets( + self, + request: securitycenter_service.ListAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsPager: + r"""Lists an organization's assets. + + Args: + request (:class:`~.securitycenter_service.ListAssetsRequest`): + The request object. Request message for listing assets. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListAssetsPager: + Response message for listing assets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + + request = securitycenter_service.ListAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_assets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAssetsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def list_findings( + self, + request: securitycenter_service.ListFindingsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFindingsPager: + r"""Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings + + Args: + request (:class:`~.securitycenter_service.ListFindingsRequest`): + The request object. Request message for listing + findings. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListFindingsPager: + Response message for listing + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + + request = securitycenter_service.ListFindingsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_findings, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListFindingsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def list_notification_configs( + self, + request: securitycenter_service.ListNotificationConfigsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListNotificationConfigsPager: + r"""Lists notification configs. + + Args: + request (:class:`~.securitycenter_service.ListNotificationConfigsRequest`): + The request object. Request message for listing + notification configs. + parent (:class:`str`): + Required. Name of the organization to list notification + configs. Its format is + "organizations/[organization_id]". + This corresponds to the ``parent`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListNotificationConfigsPager: + Response message for listing + notification configs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.ListNotificationConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_notification_configs, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListNotificationConfigsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def list_sources( + self, + request: securitycenter_service.ListSourcesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSourcesPager: + r"""Lists all sources belonging to an organization. + + Args: + request (:class:`~.securitycenter_service.ListSourcesRequest`): + The request object. Request message for listing sources. + parent (:class:`str`): + Required. Resource name of the parent of sources to + list. Its format should be + "organizations/[organization_id]". + This corresponds to the ``parent`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListSourcesPager: + Response message for listing sources. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.ListSourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_sources, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListSourcesPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def run_asset_discovery( + self, + request: securitycenter_service.RunAssetDiscoveryRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Args: + request (:class:`~.securitycenter_service.RunAssetDiscoveryRequest`): + The request object. Request message for running asset + discovery for an organization. + parent (:class:`str`): + Required. Name of the organization to run asset + discovery for. Its format is + "organizations/[organization_id]". + This corresponds to the ``parent`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.run_asset_discovery_response.RunAssetDiscoveryResponse``: + Response of asset discovery run + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.RunAssetDiscoveryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.run_asset_discovery, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + run_asset_discovery_response.RunAssetDiscoveryResponse, + metadata_type=empty.Empty, + ) + + # Done; return the response. + return response + + def set_finding_state( + self, + request: securitycenter_service.SetFindingStateRequest = None, + *, + name: str = None, + state: finding.Finding.State = None, + start_time: timestamp.Timestamp = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of a finding. + + Args: + request (:class:`~.securitycenter_service.SetFindingStateRequest`): + The request object. Request message for updating a + finding's state. + name (:class:`str`): + Required. The relative resource name of the finding. + See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (:class:`~.finding.Finding.State`): + Required. The desired State of the + finding. + This corresponds to the ``state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + start_time (:class:`~.timestamp.Timestamp`): + Required. The time at which the + updated state takes effect. + This corresponds to the ``start_time`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.finding.Finding: + Security Command Center finding. + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name, state, start_time]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.SetFindingStateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if state is not None: + request.state = state + if start_time is not None: + request.start_time = start_time + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_finding_state, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def set_iam_policy( + self, + request: iam_policy.SetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Sets the access control policy on the specified + Source. + + Args: + request (:class:`~.iam_policy.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + This corresponds to the ``resource`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([resource]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.SetIamPolicyRequest(**request) + + elif not request: + request = iam_policy.SetIamPolicyRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: iam_policy.TestIamPermissionsRequest = None, + *, + resource: str = None, + permissions: Sequence[str] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy.TestIamPermissionsResponse: + r"""Returns the permissions that a caller has on the + specified source. + + Args: + request (:class:`~.iam_policy.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`Sequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + This corresponds to the ``permissions`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.iam_policy.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([resource, permissions]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.TestIamPermissionsRequest(**request) + + elif not request: + request = iam_policy.TestIamPermissionsRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.resource = resource + + if permissions: + request.permissions.extend(permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_finding( + self, + request: securitycenter_service.UpdateFindingRequest = None, + *, + finding: gcs_finding.Finding = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Args: + request (:class:`~.securitycenter_service.UpdateFindingRequest`): + The request object. Request message for updating or + creating a finding. + finding (:class:`~.gcs_finding.Finding`): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must be alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + This corresponds to the ``finding`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_finding.Finding: + Security Command Center finding. + A finding is a record of assessment data + like security, risk, health, or privacy, + that is ingested into Security Command + Center for presentation, notification, + analysis, policy testing, and + enforcement. For example, a cross-site + scripting (XSS) vulnerability in an App + Engine application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([finding]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.UpdateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.update_finding, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("finding.name", request.finding.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_notification_config( + self, + request: securitycenter_service.UpdateNotificationConfigRequest = None, + *, + notification_config: gcs_notification_config.NotificationConfig = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Args: + request (:class:`~.securitycenter_service.UpdateNotificationConfigRequest`): + The request object. Request message for updating a + notification config. + notification_config (:class:`~.gcs_notification_config.NotificationConfig`): + Required. The notification config to + update. + This corresponds to the ``notification_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + The FieldMask to use when updating + the notification config. + If empty all mutable fields will be + updated. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_notification_config.NotificationConfig: + Cloud Security Command Center (Cloud + SCC) notification configs. + A notification config is a Cloud SCC + resource that contains the configuration + to send notifications for create/update + events of findings, assets and etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([notification_config, update_mask]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.UpdateNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if notification_config is not None: + request.notification_config = notification_config + 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 = gapic_v1.method.wrap_method( + self._transport.update_notification_config, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("notification_config.name", request.notification_config.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_organization_settings( + self, + request: securitycenter_service.UpdateOrganizationSettingsRequest = None, + *, + organization_settings: gcs_organization_settings.OrganizationSettings = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Updates an organization's settings. + + Args: + request (:class:`~.securitycenter_service.UpdateOrganizationSettingsRequest`): + The request object. Request message for updating an + organization's settings. + organization_settings (:class:`~.gcs_organization_settings.OrganizationSettings`): + Required. The organization settings + resource to update. + This corresponds to the ``organization_settings`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_organization_settings.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([organization_settings]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.UpdateOrganizationSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if organization_settings is not None: + request.organization_settings = organization_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.update_organization_settings, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("organization_settings.name", request.organization_settings.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_source( + self, + request: securitycenter_service.UpdateSourceRequest = None, + *, + source: gcs_source.Source = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Updates a source. + + Args: + request (:class:`~.securitycenter_service.UpdateSourceRequest`): + The request object. Request message for updating a + source. + source (:class:`~.gcs_source.Source`): + Required. The source resource to + update. + This corresponds to the ``source`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, and other tools. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([source]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.UpdateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.update_source, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("source.name", request.source.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_security_marks( + self, + request: securitycenter_service.UpdateSecurityMarksRequest = None, + *, + security_marks: gcs_security_marks.SecurityMarks = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. + + Args: + request (:class:`~.securitycenter_service.UpdateSecurityMarksRequest`): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (:class:`~.gcs_security_marks.SecurityMarks`): + Required. The security marks resource + to update. + This corresponds to the ``security_marks`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_security_marks.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([security_marks]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.UpdateSecurityMarksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if security_marks is not None: + request.security_marks = security_marks + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.update_security_marks, + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_marks.name", request.security_marks.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-securitycenter", + ).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +__all__ = ("SecurityCenterClient",) diff --git a/google/cloud/securitycenter_v1/services/security_center/pagers.py b/google/cloud/securitycenter_v1/services/security_center/pagers.py new file mode 100644 index 00000000..98a0cc03 --- /dev/null +++ b/google/cloud/securitycenter_v1/services/security_center/pagers.py @@ -0,0 +1,804 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple + +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import source + + +class GroupAssetsPager: + """A pager for iterating through ``group_assets`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.GroupAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GroupAssets`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.GroupAssetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., securitycenter_service.GroupAssetsResponse], + request: securitycenter_service.GroupAssetsRequest, + response: securitycenter_service.GroupAssetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.GroupAssetsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.GroupAssetsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.GroupAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.GroupAssetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[securitycenter_service.GroupResult]: + for page in self.pages: + yield from page.group_by_results + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class GroupAssetsAsyncPager: + """A pager for iterating through ``group_assets`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.GroupAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GroupAssets`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.GroupAssetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[securitycenter_service.GroupAssetsResponse]], + request: securitycenter_service.GroupAssetsRequest, + response: securitycenter_service.GroupAssetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.GroupAssetsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.GroupAssetsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.GroupAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.GroupAssetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[securitycenter_service.GroupResult]: + async def async_generator(): + async for page in self.pages: + for response in page.group_by_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class GroupFindingsPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.GroupFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.GroupFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., securitycenter_service.GroupFindingsResponse], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.GroupFindingsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.GroupFindingsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.GroupFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.GroupFindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[securitycenter_service.GroupResult]: + for page in self.pages: + yield from page.group_by_results + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class GroupFindingsAsyncPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.GroupFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.GroupFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[securitycenter_service.GroupFindingsResponse]], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.GroupFindingsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.GroupFindingsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.GroupFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterable[securitycenter_service.GroupFindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[securitycenter_service.GroupResult]: + async def async_generator(): + async for page in self.pages: + for response in page.group_by_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAssetsPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.ListAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``list_assets_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``list_assets_results`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.ListAssetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., securitycenter_service.ListAssetsResponse], + request: securitycenter_service.ListAssetsRequest, + response: securitycenter_service.ListAssetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListAssetsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.ListAssetsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.ListAssetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__( + self, + ) -> Iterable[securitycenter_service.ListAssetsResponse.ListAssetsResult]: + for page in self.pages: + yield from page.list_assets_results + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAssetsAsyncPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.ListAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``list_assets_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``list_assets_results`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.ListAssetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[securitycenter_service.ListAssetsResponse]], + request: securitycenter_service.ListAssetsRequest, + response: securitycenter_service.ListAssetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListAssetsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.ListAssetsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.ListAssetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__( + self, + ) -> AsyncIterable[securitycenter_service.ListAssetsResponse.ListAssetsResult]: + async def async_generator(): + async for page in self.pages: + for response in page.list_assets_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListFindingsPager: + """A pager for iterating through ``list_findings`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.ListFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``list_findings_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``list_findings_results`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.ListFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., securitycenter_service.ListFindingsResponse], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.ListFindingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListFindingsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.ListFindingsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.ListFindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__( + self, + ) -> Iterable[securitycenter_service.ListFindingsResponse.ListFindingsResult]: + for page in self.pages: + yield from page.list_findings_results + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListFindingsAsyncPager: + """A pager for iterating through ``list_findings`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.ListFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``list_findings_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``list_findings_results`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.ListFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[securitycenter_service.ListFindingsResponse]], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.ListFindingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListFindingsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.ListFindingsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.ListFindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__( + self, + ) -> AsyncIterable[securitycenter_service.ListFindingsResponse.ListFindingsResult]: + async def async_generator(): + async for page in self.pages: + for response in page.list_findings_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListNotificationConfigsPager: + """A pager for iterating through ``list_notification_configs`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.ListNotificationConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``notification_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListNotificationConfigs`` requests and continue to iterate + through the ``notification_configs`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.ListNotificationConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., securitycenter_service.ListNotificationConfigsResponse], + request: securitycenter_service.ListNotificationConfigsRequest, + response: securitycenter_service.ListNotificationConfigsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListNotificationConfigsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.ListNotificationConfigsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListNotificationConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.ListNotificationConfigsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[notification_config.NotificationConfig]: + for page in self.pages: + yield from page.notification_configs + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListNotificationConfigsAsyncPager: + """A pager for iterating through ``list_notification_configs`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.ListNotificationConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``notification_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListNotificationConfigs`` requests and continue to iterate + through the ``notification_configs`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.ListNotificationConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[securitycenter_service.ListNotificationConfigsResponse] + ], + request: securitycenter_service.ListNotificationConfigsRequest, + response: securitycenter_service.ListNotificationConfigsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListNotificationConfigsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.ListNotificationConfigsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListNotificationConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterable[securitycenter_service.ListNotificationConfigsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[notification_config.NotificationConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.notification_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSourcesPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.ListSourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.ListSourcesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., securitycenter_service.ListSourcesResponse], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListSourcesRequest`): + The initial request object. + response (:class:`~.securitycenter_service.ListSourcesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListSourcesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.ListSourcesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[source.Source]: + for page in self.pages: + yield from page.sources + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSourcesAsyncPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.ListSourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.ListSourcesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[securitycenter_service.ListSourcesResponse]], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListSourcesRequest`): + The initial request object. + response (:class:`~.securitycenter_service.ListSourcesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListSourcesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.ListSourcesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[source.Source]: + async def async_generator(): + async for page in self.pages: + for response in page.sources: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/securitycenter_v1/services/security_center/transports/__init__.py b/google/cloud/securitycenter_v1/services/security_center/transports/__init__.py new file mode 100644 index 00000000..20423f2a --- /dev/null +++ b/google/cloud/securitycenter_v1/services/security_center/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 typing import Dict, Type + +from .base import SecurityCenterTransport +from .grpc import SecurityCenterGrpcTransport +from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] +_transport_registry["grpc"] = SecurityCenterGrpcTransport +_transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport + + +__all__ = ( + "SecurityCenterTransport", + "SecurityCenterGrpcTransport", + "SecurityCenterGrpcAsyncIOTransport", +) diff --git a/google/cloud/securitycenter_v1/services/security_center/transports/base.py b/google/cloud/securitycenter_v1/services/security_center/transports/base.py new file mode 100644 index 00000000..189a0d3b --- /dev/null +++ b/google/cloud/securitycenter_v1/services/security_center/transports/base.py @@ -0,0 +1,354 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 +import typing + +from google import auth +from google.api_core import exceptions # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.securitycenter_v1.types import finding +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import ( + notification_config as gcs_notification_config, +) +from google.cloud.securitycenter_v1.types import organization_settings +from google.cloud.securitycenter_v1.types import ( + organization_settings as gcs_organization_settings, +) +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import source +from google.cloud.securitycenter_v1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.longrunning import operations_pb2 as operations # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + + +class SecurityCenterTransport(abc.ABC): + """Abstract transport class for SecurityCenter.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + def __init__( + self, + *, + host: str = "securitycenter.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + 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]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_source( + self, + ) -> typing.Callable[ + [securitycenter_service.CreateSourceRequest], + typing.Union[gcs_source.Source, typing.Awaitable[gcs_source.Source]], + ]: + raise NotImplementedError() + + @property + def create_finding( + self, + ) -> typing.Callable[ + [securitycenter_service.CreateFindingRequest], + typing.Union[gcs_finding.Finding, typing.Awaitable[gcs_finding.Finding]], + ]: + raise NotImplementedError() + + @property + def create_notification_config( + self, + ) -> typing.Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + typing.Union[ + gcs_notification_config.NotificationConfig, + typing.Awaitable[gcs_notification_config.NotificationConfig], + ], + ]: + raise NotImplementedError() + + @property + def delete_notification_config( + self, + ) -> typing.Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> typing.Callable[ + [iam_policy.GetIamPolicyRequest], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ]: + raise NotImplementedError() + + @property + def get_notification_config( + self, + ) -> typing.Callable[ + [securitycenter_service.GetNotificationConfigRequest], + typing.Union[ + notification_config.NotificationConfig, + typing.Awaitable[notification_config.NotificationConfig], + ], + ]: + raise NotImplementedError() + + @property + def get_organization_settings( + self, + ) -> typing.Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + typing.Union[ + organization_settings.OrganizationSettings, + typing.Awaitable[organization_settings.OrganizationSettings], + ], + ]: + raise NotImplementedError() + + @property + def get_source( + self, + ) -> typing.Callable[ + [securitycenter_service.GetSourceRequest], + typing.Union[source.Source, typing.Awaitable[source.Source]], + ]: + raise NotImplementedError() + + @property + def group_assets( + self, + ) -> typing.Callable[ + [securitycenter_service.GroupAssetsRequest], + typing.Union[ + securitycenter_service.GroupAssetsResponse, + typing.Awaitable[securitycenter_service.GroupAssetsResponse], + ], + ]: + raise NotImplementedError() + + @property + def group_findings( + self, + ) -> typing.Callable[ + [securitycenter_service.GroupFindingsRequest], + typing.Union[ + securitycenter_service.GroupFindingsResponse, + typing.Awaitable[securitycenter_service.GroupFindingsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_assets( + self, + ) -> typing.Callable[ + [securitycenter_service.ListAssetsRequest], + typing.Union[ + securitycenter_service.ListAssetsResponse, + typing.Awaitable[securitycenter_service.ListAssetsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_findings( + self, + ) -> typing.Callable[ + [securitycenter_service.ListFindingsRequest], + typing.Union[ + securitycenter_service.ListFindingsResponse, + typing.Awaitable[securitycenter_service.ListFindingsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_notification_configs( + self, + ) -> typing.Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + typing.Union[ + securitycenter_service.ListNotificationConfigsResponse, + typing.Awaitable[securitycenter_service.ListNotificationConfigsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_sources( + self, + ) -> typing.Callable[ + [securitycenter_service.ListSourcesRequest], + typing.Union[ + securitycenter_service.ListSourcesResponse, + typing.Awaitable[securitycenter_service.ListSourcesResponse], + ], + ]: + raise NotImplementedError() + + @property + def run_asset_discovery( + self, + ) -> typing.Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + @property + def set_finding_state( + self, + ) -> typing.Callable[ + [securitycenter_service.SetFindingStateRequest], + typing.Union[finding.Finding, typing.Awaitable[finding.Finding]], + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> typing.Callable[ + [iam_policy.SetIamPolicyRequest], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> typing.Callable[ + [iam_policy.TestIamPermissionsRequest], + typing.Union[ + iam_policy.TestIamPermissionsResponse, + typing.Awaitable[iam_policy.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def update_finding( + self, + ) -> typing.Callable[ + [securitycenter_service.UpdateFindingRequest], + typing.Union[gcs_finding.Finding, typing.Awaitable[gcs_finding.Finding]], + ]: + raise NotImplementedError() + + @property + def update_notification_config( + self, + ) -> typing.Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + typing.Union[ + gcs_notification_config.NotificationConfig, + typing.Awaitable[gcs_notification_config.NotificationConfig], + ], + ]: + raise NotImplementedError() + + @property + def update_organization_settings( + self, + ) -> typing.Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + typing.Union[ + gcs_organization_settings.OrganizationSettings, + typing.Awaitable[gcs_organization_settings.OrganizationSettings], + ], + ]: + raise NotImplementedError() + + @property + def update_source( + self, + ) -> typing.Callable[ + [securitycenter_service.UpdateSourceRequest], + typing.Union[gcs_source.Source, typing.Awaitable[gcs_source.Source]], + ]: + raise NotImplementedError() + + @property + def update_security_marks( + self, + ) -> typing.Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + typing.Union[ + gcs_security_marks.SecurityMarks, + typing.Awaitable[gcs_security_marks.SecurityMarks], + ], + ]: + raise NotImplementedError() + + +__all__ = ("SecurityCenterTransport",) diff --git a/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py b/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py new file mode 100644 index 00000000..c0900c9e --- /dev/null +++ b/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py @@ -0,0 +1,900 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + + +import grpc # type: ignore + +from google.cloud.securitycenter_v1.types import finding +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import ( + notification_config as gcs_notification_config, +) +from google.cloud.securitycenter_v1.types import organization_settings +from google.cloud.securitycenter_v1.types import ( + organization_settings as gcs_organization_settings, +) +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import source +from google.cloud.securitycenter_v1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.longrunning import operations_pb2 as operations # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import SecurityCenterTransport + + +class SecurityCenterGrpcTransport(SecurityCenterTransport): + """gRPC backend transport for SecurityCenter. + + V1 APIs for Security Center service. + + 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 = "securitycenter.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + 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 ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): 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 applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + 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. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + @classmethod + def create_channel( + cls, + host: str = "securitycenter.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[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]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional 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. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def create_source( + self, + ) -> Callable[[securitycenter_service.CreateSourceRequest], gcs_source.Source]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + ~.Source]: + 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_source" not in self._stubs: + self._stubs["create_source"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/CreateSource", + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs["create_source"] + + @property + def create_finding( + self, + ) -> Callable[[securitycenter_service.CreateFindingRequest], gcs_finding.Finding]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + ~.Finding]: + 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_finding" not in self._stubs: + self._stubs["create_finding"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/CreateFinding", + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs["create_finding"] + + @property + def create_notification_config( + self, + ) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + gcs_notification_config.NotificationConfig, + ]: + r"""Return a callable for the create notification config method over gRPC. + + Creates a notification config. + + Returns: + Callable[[~.CreateNotificationConfigRequest], + ~.NotificationConfig]: + 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_notification_config" not in self._stubs: + self._stubs["create_notification_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/CreateNotificationConfig", + request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs["create_notification_config"] + + @property + def delete_notification_config( + self, + ) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], empty.Empty + ]: + r"""Return a callable for the delete notification config method over gRPC. + + Deletes a notification config. + + Returns: + Callable[[~.DeleteNotificationConfigRequest], + ~.Empty]: + 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 "delete_notification_config" not in self._stubs: + self._stubs["delete_notification_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/DeleteNotificationConfig", + request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_notification_config"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy.GetIamPolicyRequest], policy.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the access control policy on the specified + Source. + + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + 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 "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/GetIamPolicy", + request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def get_notification_config( + self, + ) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + notification_config.NotificationConfig, + ]: + r"""Return a callable for the get notification config method over gRPC. + + Gets a notification config. + + Returns: + Callable[[~.GetNotificationConfigRequest], + ~.NotificationConfig]: + 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 "get_notification_config" not in self._stubs: + self._stubs["get_notification_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/GetNotificationConfig", + request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, + response_deserializer=notification_config.NotificationConfig.deserialize, + ) + return self._stubs["get_notification_config"] + + @property + def get_organization_settings( + self, + ) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + organization_settings.OrganizationSettings, + ]: + r"""Return a callable for the get organization settings method over gRPC. + + Gets the settings for an organization. + + Returns: + Callable[[~.GetOrganizationSettingsRequest], + ~.OrganizationSettings]: + 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 "get_organization_settings" not in self._stubs: + self._stubs["get_organization_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/GetOrganizationSettings", + request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, + response_deserializer=organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs["get_organization_settings"] + + @property + def get_source( + self, + ) -> Callable[[securitycenter_service.GetSourceRequest], source.Source]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + ~.Source]: + 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 "get_source" not in self._stubs: + self._stubs["get_source"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/GetSource", + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs["get_source"] + + @property + def group_assets( + self, + ) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + securitycenter_service.GroupAssetsResponse, + ]: + r"""Return a callable for the group assets method over gRPC. + + Filters an organization's assets and groups them by + their specified properties. + + Returns: + Callable[[~.GroupAssetsRequest], + ~.GroupAssetsResponse]: + 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 "group_assets" not in self._stubs: + self._stubs["group_assets"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/GroupAssets", + request_serializer=securitycenter_service.GroupAssetsRequest.serialize, + response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, + ) + return self._stubs["group_assets"] + + @property + def group_findings( + self, + ) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + securitycenter_service.GroupFindingsResponse, + ]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings + + Returns: + Callable[[~.GroupFindingsRequest], + ~.GroupFindingsResponse]: + 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 "group_findings" not in self._stubs: + self._stubs["group_findings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/GroupFindings", + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs["group_findings"] + + @property + def list_assets( + self, + ) -> Callable[ + [securitycenter_service.ListAssetsRequest], + securitycenter_service.ListAssetsResponse, + ]: + r"""Return a callable for the list assets method over gRPC. + + Lists an organization's assets. + + Returns: + Callable[[~.ListAssetsRequest], + ~.ListAssetsResponse]: + 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 "list_assets" not in self._stubs: + self._stubs["list_assets"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/ListAssets", + request_serializer=securitycenter_service.ListAssetsRequest.serialize, + response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, + ) + return self._stubs["list_assets"] + + @property + def list_findings( + self, + ) -> Callable[ + [securitycenter_service.ListFindingsRequest], + securitycenter_service.ListFindingsResponse, + ]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings + + Returns: + Callable[[~.ListFindingsRequest], + ~.ListFindingsResponse]: + 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 "list_findings" not in self._stubs: + self._stubs["list_findings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/ListFindings", + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs["list_findings"] + + @property + def list_notification_configs( + self, + ) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + securitycenter_service.ListNotificationConfigsResponse, + ]: + r"""Return a callable for the list notification configs method over gRPC. + + Lists notification configs. + + Returns: + Callable[[~.ListNotificationConfigsRequest], + ~.ListNotificationConfigsResponse]: + 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 "list_notification_configs" not in self._stubs: + self._stubs["list_notification_configs"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/ListNotificationConfigs", + request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, + ) + return self._stubs["list_notification_configs"] + + @property + def list_sources( + self, + ) -> Callable[ + [securitycenter_service.ListSourcesRequest], + securitycenter_service.ListSourcesResponse, + ]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + ~.ListSourcesResponse]: + 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 "list_sources" not in self._stubs: + self._stubs["list_sources"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/ListSources", + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs["list_sources"] + + @property + def run_asset_discovery( + self, + ) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], operations.Operation + ]: + r"""Return a callable for the run asset discovery method over gRPC. + + Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Returns: + Callable[[~.RunAssetDiscoveryRequest], + ~.Operation]: + 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 "run_asset_discovery" not in self._stubs: + self._stubs["run_asset_discovery"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/RunAssetDiscovery", + request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["run_asset_discovery"] + + @property + def set_finding_state( + self, + ) -> Callable[[securitycenter_service.SetFindingStateRequest], finding.Finding]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. + + Returns: + Callable[[~.SetFindingStateRequest], + ~.Finding]: + 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 "set_finding_state" not in self._stubs: + self._stubs["set_finding_state"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/SetFindingState", + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs["set_finding_state"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy.SetIamPolicyRequest], policy.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the access control policy on the specified + Source. + + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + 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 "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/SetIamPolicy", + request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy.TestIamPermissionsRequest], iam_policy.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns the permissions that a caller has on the + specified source. + + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + 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 "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/TestIamPermissions", + request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def update_finding( + self, + ) -> Callable[[securitycenter_service.UpdateFindingRequest], gcs_finding.Finding]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + ~.Finding]: + 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_finding" not in self._stubs: + self._stubs["update_finding"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/UpdateFinding", + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs["update_finding"] + + @property + def update_notification_config( + self, + ) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + gcs_notification_config.NotificationConfig, + ]: + r"""Return a callable for the update notification config method over gRPC. + + Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Returns: + Callable[[~.UpdateNotificationConfigRequest], + ~.NotificationConfig]: + 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_notification_config" not in self._stubs: + self._stubs["update_notification_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/UpdateNotificationConfig", + request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs["update_notification_config"] + + @property + def update_organization_settings( + self, + ) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + gcs_organization_settings.OrganizationSettings, + ]: + r"""Return a callable for the update organization settings method over gRPC. + + Updates an organization's settings. + + Returns: + Callable[[~.UpdateOrganizationSettingsRequest], + ~.OrganizationSettings]: + 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_organization_settings" not in self._stubs: + self._stubs["update_organization_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/UpdateOrganizationSettings", + request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, + response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs["update_organization_settings"] + + @property + def update_source( + self, + ) -> Callable[[securitycenter_service.UpdateSourceRequest], gcs_source.Source]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + ~.Source]: + 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_source" not in self._stubs: + self._stubs["update_source"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/UpdateSource", + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs["update_source"] + + @property + def update_security_marks( + self, + ) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + gcs_security_marks.SecurityMarks, + ]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + ~.SecurityMarks]: + 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_security_marks" not in self._stubs: + self._stubs["update_security_marks"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/UpdateSecurityMarks", + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs["update_security_marks"] + + +__all__ = ("SecurityCenterGrpcTransport",) diff --git a/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py b/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py new file mode 100644 index 00000000..e362f98a --- /dev/null +++ b/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py @@ -0,0 +1,905 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.securitycenter_v1.types import finding +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import notification_config +from google.cloud.securitycenter_v1.types import ( + notification_config as gcs_notification_config, +) +from google.cloud.securitycenter_v1.types import organization_settings +from google.cloud.securitycenter_v1.types import ( + organization_settings as gcs_organization_settings, +) +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import securitycenter_service +from google.cloud.securitycenter_v1.types import source +from google.cloud.securitycenter_v1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.longrunning import operations_pb2 as operations # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import SecurityCenterTransport +from .grpc import SecurityCenterGrpcTransport + + +class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): + """gRPC AsyncIO backend transport for SecurityCenter. + + V1 APIs for Security Center service. + + 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 = "securitycenter.googleapis.com", + credentials: 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: + address (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]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional 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. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "securitycenter.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + 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 ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional 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[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): 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 applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + 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. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} + + @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. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def create_source( + self, + ) -> Callable[ + [securitycenter_service.CreateSourceRequest], Awaitable[gcs_source.Source] + ]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + Awaitable[~.Source]]: + 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_source" not in self._stubs: + self._stubs["create_source"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/CreateSource", + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs["create_source"] + + @property + def create_finding( + self, + ) -> Callable[ + [securitycenter_service.CreateFindingRequest], Awaitable[gcs_finding.Finding] + ]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + Awaitable[~.Finding]]: + 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_finding" not in self._stubs: + self._stubs["create_finding"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/CreateFinding", + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs["create_finding"] + + @property + def create_notification_config( + self, + ) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + Awaitable[gcs_notification_config.NotificationConfig], + ]: + r"""Return a callable for the create notification config method over gRPC. + + Creates a notification config. + + Returns: + Callable[[~.CreateNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + 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_notification_config" not in self._stubs: + self._stubs["create_notification_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/CreateNotificationConfig", + request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs["create_notification_config"] + + @property + def delete_notification_config( + self, + ) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], Awaitable[empty.Empty] + ]: + r"""Return a callable for the delete notification config method over gRPC. + + Deletes a notification config. + + Returns: + Callable[[~.DeleteNotificationConfigRequest], + Awaitable[~.Empty]]: + 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 "delete_notification_config" not in self._stubs: + self._stubs["delete_notification_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/DeleteNotificationConfig", + request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_notification_config"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy.GetIamPolicyRequest], Awaitable[policy.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the access control policy on the specified + Source. + + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.Policy]]: + 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 "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/GetIamPolicy", + request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def get_notification_config( + self, + ) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + Awaitable[notification_config.NotificationConfig], + ]: + r"""Return a callable for the get notification config method over gRPC. + + Gets a notification config. + + Returns: + Callable[[~.GetNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + 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 "get_notification_config" not in self._stubs: + self._stubs["get_notification_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/GetNotificationConfig", + request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, + response_deserializer=notification_config.NotificationConfig.deserialize, + ) + return self._stubs["get_notification_config"] + + @property + def get_organization_settings( + self, + ) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + Awaitable[organization_settings.OrganizationSettings], + ]: + r"""Return a callable for the get organization settings method over gRPC. + + Gets the settings for an organization. + + Returns: + Callable[[~.GetOrganizationSettingsRequest], + Awaitable[~.OrganizationSettings]]: + 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 "get_organization_settings" not in self._stubs: + self._stubs["get_organization_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/GetOrganizationSettings", + request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, + response_deserializer=organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs["get_organization_settings"] + + @property + def get_source( + self, + ) -> Callable[[securitycenter_service.GetSourceRequest], Awaitable[source.Source]]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + Awaitable[~.Source]]: + 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 "get_source" not in self._stubs: + self._stubs["get_source"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/GetSource", + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs["get_source"] + + @property + def group_assets( + self, + ) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + Awaitable[securitycenter_service.GroupAssetsResponse], + ]: + r"""Return a callable for the group assets method over gRPC. + + Filters an organization's assets and groups them by + their specified properties. + + Returns: + Callable[[~.GroupAssetsRequest], + Awaitable[~.GroupAssetsResponse]]: + 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 "group_assets" not in self._stubs: + self._stubs["group_assets"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/GroupAssets", + request_serializer=securitycenter_service.GroupAssetsRequest.serialize, + response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, + ) + return self._stubs["group_assets"] + + @property + def group_findings( + self, + ) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + Awaitable[securitycenter_service.GroupFindingsResponse], + ]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings + + Returns: + Callable[[~.GroupFindingsRequest], + Awaitable[~.GroupFindingsResponse]]: + 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 "group_findings" not in self._stubs: + self._stubs["group_findings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/GroupFindings", + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs["group_findings"] + + @property + def list_assets( + self, + ) -> Callable[ + [securitycenter_service.ListAssetsRequest], + Awaitable[securitycenter_service.ListAssetsResponse], + ]: + r"""Return a callable for the list assets method over gRPC. + + Lists an organization's assets. + + Returns: + Callable[[~.ListAssetsRequest], + Awaitable[~.ListAssetsResponse]]: + 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 "list_assets" not in self._stubs: + self._stubs["list_assets"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/ListAssets", + request_serializer=securitycenter_service.ListAssetsRequest.serialize, + response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, + ) + return self._stubs["list_assets"] + + @property + def list_findings( + self, + ) -> Callable[ + [securitycenter_service.ListFindingsRequest], + Awaitable[securitycenter_service.ListFindingsResponse], + ]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: /v1/organizations/{organization_id}/sources/-/findings + + Returns: + Callable[[~.ListFindingsRequest], + Awaitable[~.ListFindingsResponse]]: + 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 "list_findings" not in self._stubs: + self._stubs["list_findings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/ListFindings", + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs["list_findings"] + + @property + def list_notification_configs( + self, + ) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + Awaitable[securitycenter_service.ListNotificationConfigsResponse], + ]: + r"""Return a callable for the list notification configs method over gRPC. + + Lists notification configs. + + Returns: + Callable[[~.ListNotificationConfigsRequest], + Awaitable[~.ListNotificationConfigsResponse]]: + 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 "list_notification_configs" not in self._stubs: + self._stubs["list_notification_configs"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/ListNotificationConfigs", + request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, + ) + return self._stubs["list_notification_configs"] + + @property + def list_sources( + self, + ) -> Callable[ + [securitycenter_service.ListSourcesRequest], + Awaitable[securitycenter_service.ListSourcesResponse], + ]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + Awaitable[~.ListSourcesResponse]]: + 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 "list_sources" not in self._stubs: + self._stubs["list_sources"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/ListSources", + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs["list_sources"] + + @property + def run_asset_discovery( + self, + ) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + Awaitable[operations.Operation], + ]: + r"""Return a callable for the run asset discovery method over gRPC. + + Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Returns: + Callable[[~.RunAssetDiscoveryRequest], + Awaitable[~.Operation]]: + 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 "run_asset_discovery" not in self._stubs: + self._stubs["run_asset_discovery"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/RunAssetDiscovery", + request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["run_asset_discovery"] + + @property + def set_finding_state( + self, + ) -> Callable[ + [securitycenter_service.SetFindingStateRequest], Awaitable[finding.Finding] + ]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. + + Returns: + Callable[[~.SetFindingStateRequest], + Awaitable[~.Finding]]: + 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 "set_finding_state" not in self._stubs: + self._stubs["set_finding_state"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/SetFindingState", + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs["set_finding_state"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy.SetIamPolicyRequest], Awaitable[policy.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the access control policy on the specified + Source. + + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.Policy]]: + 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 "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/SetIamPolicy", + request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy.TestIamPermissionsRequest], + Awaitable[iam_policy.TestIamPermissionsResponse], + ]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns the permissions that a caller has on the + specified source. + + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.TestIamPermissionsResponse]]: + 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 "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/TestIamPermissions", + request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def update_finding( + self, + ) -> Callable[ + [securitycenter_service.UpdateFindingRequest], Awaitable[gcs_finding.Finding] + ]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + Awaitable[~.Finding]]: + 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_finding" not in self._stubs: + self._stubs["update_finding"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/UpdateFinding", + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs["update_finding"] + + @property + def update_notification_config( + self, + ) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + Awaitable[gcs_notification_config.NotificationConfig], + ]: + r"""Return a callable for the update notification config method over gRPC. + + Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Returns: + Callable[[~.UpdateNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + 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_notification_config" not in self._stubs: + self._stubs["update_notification_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/UpdateNotificationConfig", + request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs["update_notification_config"] + + @property + def update_organization_settings( + self, + ) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + Awaitable[gcs_organization_settings.OrganizationSettings], + ]: + r"""Return a callable for the update organization settings method over gRPC. + + Updates an organization's settings. + + Returns: + Callable[[~.UpdateOrganizationSettingsRequest], + Awaitable[~.OrganizationSettings]]: + 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_organization_settings" not in self._stubs: + self._stubs["update_organization_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/UpdateOrganizationSettings", + request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, + response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs["update_organization_settings"] + + @property + def update_source( + self, + ) -> Callable[ + [securitycenter_service.UpdateSourceRequest], Awaitable[gcs_source.Source] + ]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + Awaitable[~.Source]]: + 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_source" not in self._stubs: + self._stubs["update_source"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/UpdateSource", + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs["update_source"] + + @property + def update_security_marks( + self, + ) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + Awaitable[gcs_security_marks.SecurityMarks], + ]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + Awaitable[~.SecurityMarks]]: + 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_security_marks" not in self._stubs: + self._stubs["update_security_marks"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1.SecurityCenter/UpdateSecurityMarks", + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs["update_security_marks"] + + +__all__ = ("SecurityCenterGrpcAsyncIOTransport",) diff --git a/google/cloud/securitycenter_v1/types/__init__.py b/google/cloud/securitycenter_v1/types/__init__.py new file mode 100644 index 00000000..c65c45b8 --- /dev/null +++ b/google/cloud/securitycenter_v1/types/__init__.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 .security_marks import SecurityMarks +from .asset import Asset +from .finding import Finding +from .notification_config import NotificationConfig +from .resource import Resource +from .notification_message import NotificationMessage +from .organization_settings import OrganizationSettings +from .run_asset_discovery_response import RunAssetDiscoveryResponse +from .source import Source +from .securitycenter_service import ( + CreateFindingRequest, + CreateNotificationConfigRequest, + CreateSourceRequest, + DeleteNotificationConfigRequest, + GetNotificationConfigRequest, + GetOrganizationSettingsRequest, + GetSourceRequest, + GroupAssetsRequest, + GroupAssetsResponse, + GroupFindingsRequest, + GroupFindingsResponse, + GroupResult, + ListNotificationConfigsRequest, + ListNotificationConfigsResponse, + ListSourcesRequest, + ListSourcesResponse, + ListAssetsRequest, + ListAssetsResponse, + ListFindingsRequest, + ListFindingsResponse, + SetFindingStateRequest, + RunAssetDiscoveryRequest, + UpdateFindingRequest, + UpdateNotificationConfigRequest, + UpdateOrganizationSettingsRequest, + UpdateSourceRequest, + UpdateSecurityMarksRequest, +) + + +__all__ = ( + "SecurityMarks", + "Asset", + "Finding", + "NotificationConfig", + "Resource", + "NotificationMessage", + "OrganizationSettings", + "RunAssetDiscoveryResponse", + "Source", + "CreateFindingRequest", + "CreateNotificationConfigRequest", + "CreateSourceRequest", + "DeleteNotificationConfigRequest", + "GetNotificationConfigRequest", + "GetOrganizationSettingsRequest", + "GetSourceRequest", + "GroupAssetsRequest", + "GroupAssetsResponse", + "GroupFindingsRequest", + "GroupFindingsResponse", + "GroupResult", + "ListNotificationConfigsRequest", + "ListNotificationConfigsResponse", + "ListSourcesRequest", + "ListSourcesResponse", + "ListAssetsRequest", + "ListAssetsResponse", + "ListFindingsRequest", + "ListFindingsResponse", + "SetFindingStateRequest", + "RunAssetDiscoveryRequest", + "UpdateFindingRequest", + "UpdateNotificationConfigRequest", + "UpdateOrganizationSettingsRequest", + "UpdateSourceRequest", + "UpdateSecurityMarksRequest", +) diff --git a/google/cloud/securitycenter_v1/types/asset.py b/google/cloud/securitycenter_v1/types/asset.py new file mode 100644 index 00000000..d1992e53 --- /dev/null +++ b/google/cloud/securitycenter_v1/types/asset.py @@ -0,0 +1,166 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1", manifest={"Asset",}, +) + + +class Asset(proto.Message): + r"""Security Command Center representation of a Google Cloud + resource. + + The Asset is a Security Command Center resource that captures + information about a single Google Cloud resource. All + modifications to an Asset are only within the context of + Security Command Center and don't affect the referenced Google + Cloud resource. + + Attributes: + name (str): + The relative resource name of this asset. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/assets/{asset_id}". + security_center_properties (~.asset.Asset.SecurityCenterProperties): + Security Command Center managed properties. + These properties are managed by Security Command + Center and cannot be modified by the user. + resource_properties (Sequence[~.asset.Asset.ResourcePropertiesEntry]): + Resource managed properties. These properties + are managed and defined by the Google Cloud + resource and cannot be modified by the user. + security_marks (~.gcs_security_marks.SecurityMarks): + User specified security marks. These marks + are entirely managed by the user and come from + the SecurityMarks resource that belongs to the + asset. + create_time (~.timestamp.Timestamp): + The time at which the asset was created in + Security Command Center. + update_time (~.timestamp.Timestamp): + The time at which the asset was last updated, + added, or deleted in Security Command Center. + iam_policy (~.asset.Asset.IamPolicy): + Cloud IAM Policy information associated with + the Google Cloud resource described by the + Security Command Center asset. This information + is managed and defined by the Google Cloud + resource and cannot be modified by the user. + """ + + class SecurityCenterProperties(proto.Message): + r"""Security Command Center managed properties. These properties + are managed by Security Command Center and cannot be modified by + the user. + + Attributes: + resource_name (str): + The full resource name of the Google Cloud resource this + asset represents. This field is immutable after create time. + See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_type (str): + The type of the Google Cloud resource. + Examples include: APPLICATION, PROJECT, and + ORGANIZATION. This is a case insensitive field + defined by Security Command Center and/or the + producer of the resource and is immutable after + create time. + resource_parent (str): + The full resource name of the immediate parent of the + resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_project (str): + The full resource name of the project the resource belongs + to. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_owners (Sequence[str]): + Owners of the Google Cloud resource. + resource_display_name (str): + The user defined display name for this + resource. + resource_parent_display_name (str): + The user defined display name for the parent + of this resource. + resource_project_display_name (str): + The user defined display name for the project + of this resource. + """ + + resource_name = proto.Field(proto.STRING, number=1) + + resource_type = proto.Field(proto.STRING, number=2) + + resource_parent = proto.Field(proto.STRING, number=3) + + resource_project = proto.Field(proto.STRING, number=4) + + resource_owners = proto.RepeatedField(proto.STRING, number=5) + + resource_display_name = proto.Field(proto.STRING, number=6) + + resource_parent_display_name = proto.Field(proto.STRING, number=7) + + resource_project_display_name = proto.Field(proto.STRING, number=8) + + class IamPolicy(proto.Message): + r"""Cloud IAM Policy information associated with the Google Cloud + resource described by the Security Command Center asset. This + information is managed and defined by the Google Cloud resource + and cannot be modified by the user. + + Attributes: + policy_blob (str): + The JSON representation of the Policy + associated with the asset. See + https://cloud.google.com/iam/reference/rest/v1/Policy + for format details. + """ + + policy_blob = proto.Field(proto.STRING, number=1) + + name = proto.Field(proto.STRING, number=1) + + security_center_properties = proto.Field( + proto.MESSAGE, number=2, message=SecurityCenterProperties, + ) + + resource_properties = proto.MapField( + proto.STRING, proto.MESSAGE, number=7, message=struct.Value, + ) + + security_marks = proto.Field( + proto.MESSAGE, number=8, message=gcs_security_marks.SecurityMarks, + ) + + create_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) + + update_time = proto.Field(proto.MESSAGE, number=10, message=timestamp.Timestamp,) + + iam_policy = proto.Field(proto.MESSAGE, number=11, message=IamPolicy,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/finding.py b/google/cloud/securitycenter_v1/types/finding.py new file mode 100644 index 00000000..c7a5dbdc --- /dev/null +++ b/google/cloud/securitycenter_v1/types/finding.py @@ -0,0 +1,123 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1", manifest={"Finding",}, +) + + +class Finding(proto.Message): + r"""Security Command Center finding. + A finding is a record of assessment data like security, risk, + health, or privacy, that is ingested into Security Command + Center for presentation, notification, analysis, policy testing, + and enforcement. For example, a cross-site scripting (XSS) + vulnerability in an App Engine application is a finding. + + Attributes: + name (str): + The relative resource name of this finding. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}". + parent (str): + The relative resource name of the source the finding belongs + to. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + This field is immutable after creation time. For example: + "organizations/{organization_id}/sources/{source_id}". + resource_name (str): + For findings on Google Cloud resources, the full resource + name of the Google Cloud resource this finding is for. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + When the finding is for a non-Google Cloud resource, the + resourceName can be a customer or partner defined string. + This field is immutable after creation time. + state (~.finding.Finding.State): + The state of the finding. + category (str): + The additional taxonomy group within findings from a given + source. This field is immutable after creation time. + Example: "XSS_FLASH_INJECTION". + external_uri (str): + The URI that, if available, points to a web + page outside of Security Command Center where + additional information about the finding can be + found. This field is guaranteed to be either + empty or a well formed URL. + source_properties (Sequence[~.finding.Finding.SourcePropertiesEntry]): + Source specific properties. These properties are managed by + the source that writes the finding. The key names in the + source_properties map must be between 1 and 255 characters, + and must start with a letter and contain alphanumeric + characters or underscores only. + security_marks (~.gcs_security_marks.SecurityMarks): + Output only. User specified security marks. + These marks are entirely managed by the user and + come from the SecurityMarks resource that + belongs to the finding. + event_time (~.timestamp.Timestamp): + The time at which the event took place. For + example, if the finding represents an open + firewall it would capture the time the detector + believes the firewall became open. The accuracy + is determined by the detector. + create_time (~.timestamp.Timestamp): + The time at which the finding was created in + Security Command Center. + """ + + class State(proto.Enum): + r"""The state of the finding.""" + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + INACTIVE = 2 + + name = proto.Field(proto.STRING, number=1) + + parent = proto.Field(proto.STRING, number=2) + + resource_name = proto.Field(proto.STRING, number=3) + + state = proto.Field(proto.ENUM, number=4, enum=State,) + + category = proto.Field(proto.STRING, number=5) + + external_uri = proto.Field(proto.STRING, number=6) + + source_properties = proto.MapField( + proto.STRING, proto.MESSAGE, number=7, message=struct.Value, + ) + + security_marks = proto.Field( + proto.MESSAGE, number=8, message=gcs_security_marks.SecurityMarks, + ) + + event_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) + + create_time = proto.Field(proto.MESSAGE, number=10, message=timestamp.Timestamp,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/notification_config.py b/google/cloud/securitycenter_v1/types/notification_config.py new file mode 100644 index 00000000..87e4d654 --- /dev/null +++ b/google/cloud/securitycenter_v1/types/notification_config.py @@ -0,0 +1,100 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1", manifest={"NotificationConfig",}, +) + + +class NotificationConfig(proto.Message): + r"""Cloud Security Command Center (Cloud SCC) notification + configs. + A notification config is a Cloud SCC resource that contains the + configuration to send notifications for create/update events of + findings, assets and etc. + + Attributes: + name (str): + The relative resource name of this notification config. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/notificationConfigs/notify_public_bucket". + description (str): + The description of the notification config + (max of 1024 characters). + pubsub_topic (str): + The PubSub topic to send notifications to. Its format is + "projects/[project_id]/topics/[topic]". + service_account (str): + Output only. The service account that needs + "pubsub.topics.publish" permission to publish to + the PubSub topic. + streaming_config (~.notification_config.NotificationConfig.StreamingConfig): + The config for triggering streaming-based + notifications. + """ + + class StreamingConfig(proto.Message): + r"""The config for streaming-based notifications, which send each + event as soon as it is detected. + + Attributes: + filter (str): + Expression that defines the filter to apply across + create/update events of assets or findings as specified by + the event type. The expression is a list of zero or more + restrictions combined via logical operators ``AND`` and + ``OR``. Parentheses are supported, and ``OR`` has higher + precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the + corresponding resource. + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + """ + + filter = proto.Field(proto.STRING, number=1) + + name = proto.Field(proto.STRING, number=1) + + description = proto.Field(proto.STRING, number=2) + + pubsub_topic = proto.Field(proto.STRING, number=3) + + service_account = proto.Field(proto.STRING, number=4) + + streaming_config = proto.Field( + proto.MESSAGE, number=5, oneof="notify_config", message=StreamingConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/notification_message.py b/google/cloud/securitycenter_v1/types/notification_message.py new file mode 100644 index 00000000..c836cad9 --- /dev/null +++ b/google/cloud/securitycenter_v1/types/notification_message.py @@ -0,0 +1,54 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import resource as gcs_resource + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1", manifest={"NotificationMessage",}, +) + + +class NotificationMessage(proto.Message): + r"""Cloud SCC's Notification + + Attributes: + notification_config_name (str): + Name of the notification config that + generated current notification. + finding (~.gcs_finding.Finding): + If it's a Finding based notification config, + this field will be populated. + resource (~.gcs_resource.Resource): + The Cloud resource tied to this + notification's Finding. + """ + + notification_config_name = proto.Field(proto.STRING, number=1) + + finding = proto.Field( + proto.MESSAGE, number=2, oneof="event", message=gcs_finding.Finding, + ) + + resource = proto.Field(proto.MESSAGE, number=3, message=gcs_resource.Resource,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/organization_settings.py b/google/cloud/securitycenter_v1/types/organization_settings.py new file mode 100644 index 00000000..ad4bc9f8 --- /dev/null +++ b/google/cloud/securitycenter_v1/types/organization_settings.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1", manifest={"OrganizationSettings",}, +) + + +class OrganizationSettings(proto.Message): + r"""User specified settings that are attached to the Security + Command Center organization. + + Attributes: + name (str): + The relative resource name of the settings. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/organizationSettings". + enable_asset_discovery (bool): + A flag that indicates if Asset Discovery should be enabled. + If the flag is set to ``true``, then discovery of assets + will occur. If it is set to \`false, all historical assets + will remain, but discovery of future assets will not occur. + asset_discovery_config (~.organization_settings.OrganizationSettings.AssetDiscoveryConfig): + The configuration used for Asset Discovery + runs. + """ + + class AssetDiscoveryConfig(proto.Message): + r"""The configuration used for Asset Discovery runs. + + Attributes: + project_ids (Sequence[str]): + The project ids to use for filtering asset + discovery. + inclusion_mode (~.organization_settings.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): + The mode to use for filtering asset + discovery. + """ + + class InclusionMode(proto.Enum): + r"""The mode of inclusion when running Asset Discovery. Asset discovery + can be limited by explicitly identifying projects to be included or + excluded. If INCLUDE_ONLY is set, then only those projects within + the organization and their children are discovered during asset + discovery. If EXCLUDE is set, then projects that don't match those + projects are discovered during asset discovery. If neither are set, + then all projects within the organization are discovered during + asset discovery. + """ + INCLUSION_MODE_UNSPECIFIED = 0 + INCLUDE_ONLY = 1 + EXCLUDE = 2 + + project_ids = proto.RepeatedField(proto.STRING, number=1) + + inclusion_mode = proto.Field( + proto.ENUM, + number=2, + enum="OrganizationSettings.AssetDiscoveryConfig.InclusionMode", + ) + + name = proto.Field(proto.STRING, number=1) + + enable_asset_discovery = proto.Field(proto.BOOL, number=2) + + asset_discovery_config = proto.Field( + proto.MESSAGE, number=3, message=AssetDiscoveryConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/resource.py b/google/cloud/securitycenter_v1/types/resource.py new file mode 100644 index 00000000..49c709fa --- /dev/null +++ b/google/cloud/securitycenter_v1/types/resource.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1", manifest={"Resource",}, +) + + +class Resource(proto.Message): + r"""Information related to the Google Cloud resource. + + Attributes: + name (str): + The full resource name of the resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + project (str): + The full resource name of project that the + resource belongs to. + project_display_name (str): + The human readable name of project that the + resource belongs to. + parent (str): + The full resource name of resource's parent. + parent_display_name (str): + The human readable name of resource's parent. + """ + + name = proto.Field(proto.STRING, number=1) + + project = proto.Field(proto.STRING, number=2) + + project_display_name = proto.Field(proto.STRING, number=3) + + parent = proto.Field(proto.STRING, number=4) + + parent_display_name = proto.Field(proto.STRING, number=5) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py b/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py new file mode 100644 index 00000000..eeed56ef --- /dev/null +++ b/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py @@ -0,0 +1,52 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +from google.protobuf import duration_pb2 as gp_duration # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1", manifest={"RunAssetDiscoveryResponse",}, +) + + +class RunAssetDiscoveryResponse(proto.Message): + r"""Response of asset discovery run + + Attributes: + state (~.run_asset_discovery_response.RunAssetDiscoveryResponse.State): + The state of an asset discovery run. + duration (~.gp_duration.Duration): + The duration between asset discovery run + start and end + """ + + class State(proto.Enum): + r"""The state of an asset discovery run.""" + STATE_UNSPECIFIED = 0 + COMPLETED = 1 + SUPERSEDED = 2 + TERMINATED = 3 + + state = proto.Field(proto.ENUM, number=1, enum=State,) + + duration = proto.Field(proto.MESSAGE, number=2, message=gp_duration.Duration,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/security_marks.py b/google/cloud/securitycenter_v1/types/security_marks.py new file mode 100644 index 00000000..21bf0b0a --- /dev/null +++ b/google/cloud/securitycenter_v1/types/security_marks.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1", manifest={"SecurityMarks",}, +) + + +class SecurityMarks(proto.Message): + r"""User specified security marks that are attached to the parent + Security Command Center resource. Security marks are scoped + within a Security Command Center organization -- they can be + modified and viewed by all users who have proper permissions on + the organization. + + Attributes: + name (str): + The relative resource name of the SecurityMarks. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Examples: + "organizations/{organization_id}/assets/{asset_id}/securityMarks" + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks". + marks (Sequence[~.security_marks.SecurityMarks.MarksEntry]): + Mutable user specified security marks belonging to the + parent resource. Constraints are as follows: + + - Keys and values are treated as case insensitive + - Keys must be between 1 - 256 characters (inclusive) + - Keys must be letters, numbers, underscores, or dashes + - Values have leading and trailing whitespace trimmed, + remaining characters must be between 1 - 4096 characters + (inclusive) + """ + + name = proto.Field(proto.STRING, number=1) + + marks = proto.MapField(proto.STRING, proto.STRING, number=2) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/securitycenter_service.py b/google/cloud/securitycenter_v1/types/securitycenter_service.py new file mode 100644 index 00000000..1653a05b --- /dev/null +++ b/google/cloud/securitycenter_v1/types/securitycenter_service.py @@ -0,0 +1,1353 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +from google.cloud.securitycenter_v1.types import asset as gcs_asset +from google.cloud.securitycenter_v1.types import finding as gcs_finding +from google.cloud.securitycenter_v1.types import ( + notification_config as gcs_notification_config, +) +from google.cloud.securitycenter_v1.types import ( + organization_settings as gcs_organization_settings, +) +from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks +from google.cloud.securitycenter_v1.types import source as gcs_source +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import field_mask_pb2 as gp_field_mask # type: ignore +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1", + manifest={ + "CreateFindingRequest", + "CreateNotificationConfigRequest", + "CreateSourceRequest", + "DeleteNotificationConfigRequest", + "GetNotificationConfigRequest", + "GetOrganizationSettingsRequest", + "GetSourceRequest", + "GroupAssetsRequest", + "GroupAssetsResponse", + "GroupFindingsRequest", + "GroupFindingsResponse", + "GroupResult", + "ListNotificationConfigsRequest", + "ListNotificationConfigsResponse", + "ListSourcesRequest", + "ListSourcesResponse", + "ListAssetsRequest", + "ListAssetsResponse", + "ListFindingsRequest", + "ListFindingsResponse", + "SetFindingStateRequest", + "RunAssetDiscoveryRequest", + "UpdateFindingRequest", + "UpdateNotificationConfigRequest", + "UpdateOrganizationSettingsRequest", + "UpdateSourceRequest", + "UpdateSecurityMarksRequest", + }, +) + + +class CreateFindingRequest(proto.Message): + r"""Request message for creating a finding. + + Attributes: + parent (str): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + finding_id (str): + Required. Unique identifier provided by the + client within the parent scope. It must be + alphanumeric and less than or equal to 32 + characters and greater than 0 characters in + length. + finding (~.gcs_finding.Finding): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output only + fields on this resource. + """ + + parent = proto.Field(proto.STRING, number=1) + + finding_id = proto.Field(proto.STRING, number=2) + + finding = proto.Field(proto.MESSAGE, number=3, message=gcs_finding.Finding,) + + +class CreateNotificationConfigRequest(proto.Message): + r"""Request message for creating a notification config. + + Attributes: + parent (str): + Required. Resource name of the new notification config's + parent. Its format is "organizations/[organization_id]". + config_id (str): + Required. + Unique identifier provided by the client within + the parent scope. It must be between 1 and 128 + characters, and contains alphanumeric + characters, underscores or hyphens only. + notification_config (~.gcs_notification_config.NotificationConfig): + Required. The notification config being + created. The name and the service account will + be ignored as they are both output only fields + on this resource. + """ + + parent = proto.Field(proto.STRING, number=1) + + config_id = proto.Field(proto.STRING, number=2) + + notification_config = proto.Field( + proto.MESSAGE, number=3, message=gcs_notification_config.NotificationConfig, + ) + + +class CreateSourceRequest(proto.Message): + r"""Request message for creating a source. + + Attributes: + parent (str): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + source (~.gcs_source.Source): + Required. The Source being created, only the display_name + and description will be used. All other fields will be + ignored. + """ + + parent = proto.Field(proto.STRING, number=1) + + source = proto.Field(proto.MESSAGE, number=2, message=gcs_source.Source,) + + +class DeleteNotificationConfigRequest(proto.Message): + r"""Request message for deleting a notification config. + + Attributes: + name (str): + Required. Name of the notification config to delete. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_id]". + """ + + name = proto.Field(proto.STRING, number=1) + + +class GetNotificationConfigRequest(proto.Message): + r"""Request message for getting a notification config. + + Attributes: + name (str): + Required. Name of the notification config to get. Its format + is + "organizations/[organization_id]/notificationConfigs/[config_id]". + """ + + name = proto.Field(proto.STRING, number=1) + + +class GetOrganizationSettingsRequest(proto.Message): + r"""Request message for getting organization settings. + + Attributes: + name (str): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + """ + + name = proto.Field(proto.STRING, number=1) + + +class GetSourceRequest(proto.Message): + r"""Request message for getting a source. + + Attributes: + name (str): + Required. Relative resource name of the source. Its format + is "organizations/[organization_id]/source/[source_id]". + """ + + name = proto.Field(proto.STRING, number=1) + + +class GroupAssetsRequest(proto.Message): + r"""Request message for grouping by assets. + + Attributes: + parent (str): + Required. Name of the organization to groupBy. Its format is + "organizations/[organization_id]". + filter (str): + Expression that defines the filter to apply across assets. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the Asset + resource. Examples include: + + - name + - security_center_properties.resource_name + - resource_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``update_time = "2019-06-10T16:07:18-07:00"`` + ``update_time = 1560208038000`` + + - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``create_time = "2019-06-10T16:07:18-07:00"`` + ``create_time = 1560208038000`` + + - iam_policy.policy_blob: ``=``, ``:`` + + - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, + ``<=`` + + - security_marks.marks: ``=``, ``:`` + + - security_center_properties.resource_name: ``=``, ``:`` + + - security_center_properties.resource_display_name: ``=``, + ``:`` + + - security_center_properties.resource_type: ``=``, ``:`` + + - security_center_properties.resource_parent: ``=``, ``:`` + + - security_center_properties.resource_parent_display_name: + ``=``, ``:`` + + - security_center_properties.resource_project: ``=``, ``:`` + + - security_center_properties.resource_project_display_name: + ``=``, ``:`` + + - security_center_properties.resource_owners: ``=``, ``:`` + + For example, ``resource_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based on a + property existing:\ ``resource_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-resource_properties.my_property : ""`` + group_by (str): + Required. Expression that defines what assets fields to use + for grouping. The string value should follow SQL syntax: + comma separated list of fields. For example: + "security_center_properties.resource_project,security_center_properties.project". + + The following fields are supported when compare_duration is + not set: + + - security_center_properties.resource_project + - security_center_properties.resource_project_display_name + - security_center_properties.resource_type + - security_center_properties.resource_parent + - security_center_properties.resource_parent_display_name + + The following fields are supported when compare_duration is + set: + + - security_center_properties.resource_type + - security_center_properties.resource_project_display_name + - security_center_properties.resource_parent_display_name + compare_duration (~.duration.Duration): + When compare_duration is set, the GroupResult's + "state_change" property is updated to indicate whether the + asset was added, removed, or remained present during the + compare_duration period of time that precedes the read_time. + This is the time between (read_time - compare_duration) and + read_time. + + The state change value is derived based on the presence of + the asset at the two points in time. Intermediate state + changes between the two times don't affect the result. For + example, the results aren't affected if the asset is removed + and re-created again. + + Possible "state_change" values when compare_duration is + specified: + + - "ADDED": indicates that the asset was not present at the + start of compare_duration, but present at reference_time. + - "REMOVED": indicates that the asset was present at the + start of compare_duration, but not present at + reference_time. + - "ACTIVE": indicates that the asset was present at both + the start and the end of the time period defined by + compare_duration and reference_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all assets present at read_time. + + If this field is set then ``state_change`` must be a + specified field in ``group_by``. + read_time (~.timestamp.Timestamp): + Time used as a reference point when filtering + assets. The filter is limited to assets existing + at the supplied time and their values are those + at that specific time. Absence of this field + will default to the API's version of NOW. + page_token (str): + The value returned by the last ``GroupAssetsResponse``; + indicates that this is a continuation of a prior + ``GroupAssets`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field(proto.STRING, number=1) + + filter = proto.Field(proto.STRING, number=2) + + group_by = proto.Field(proto.STRING, number=3) + + compare_duration = proto.Field(proto.MESSAGE, number=4, message=duration.Duration,) + + read_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) + + page_token = proto.Field(proto.STRING, number=7) + + page_size = proto.Field(proto.INT32, number=8) + + +class GroupAssetsResponse(proto.Message): + r"""Response message for grouping by assets. + + Attributes: + group_by_results (Sequence[~.securitycenter_service.GroupResult]): + Group results. There exists an element for + each existing unique combination of + property/values. The element contains a count + for the number of times those specific + property/values appear. + read_time (~.timestamp.Timestamp): + Time used for executing the groupBy request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of results matching the + query. + """ + + @property + def raw_page(self): + return self + + group_by_results = proto.RepeatedField( + proto.MESSAGE, number=1, message="GroupResult", + ) + + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + next_page_token = proto.Field(proto.STRING, number=3) + + total_size = proto.Field(proto.INT32, number=4) + + +class GroupFindingsRequest(proto.Message): + r"""Request message for grouping by findings. + + Attributes: + parent (str): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]". To + groupBy across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/- + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - source_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - parent: ``=``, ``:`` + + - resource_name: ``=``, ``:`` + + - state: ``=``, ``:`` + + - category: ``=``, ``:`` + + - external_uri: ``=``, ``:`` + + - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``event_time = "2019-06-10T16:07:18-07:00"`` + ``event_time = 1560208038000`` + + - security_marks.marks: ``=``, ``:`` + + - source_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, + ``<=`` + + For example, ``source_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based on a + property existing: ``source_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-source_properties.my_property : ""`` + group_by (str): + Required. Expression that defines what assets fields to use + for grouping (including ``state_change``). The string value + should follow SQL syntax: comma separated list of fields. + For example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + + The following fields are supported when compare_duration is + set: + + - state_change + read_time (~.timestamp.Timestamp): + Time used as a reference point when filtering + findings. The filter is limited to findings + existing at the supplied time and their values + are those at that specific time. Absence of this + field will default to the API's version of NOW. + compare_duration (~.duration.Duration): + When compare_duration is set, the GroupResult's + "state_change" attribute is updated to indicate whether the + finding had its state changed, the finding's state remained + unchanged, or if the finding was added during the + compare_duration period of time that precedes the read_time. + This is the time between (read_time - compare_duration) and + read_time. + + The state_change value is derived based on the presence and + state of the finding at the two points in time. Intermediate + state changes between the two times don't affect the result. + For example, the results aren't affected if the finding is + made inactive and then active again. + + Possible "state_change" values when compare_duration is + specified: + + - "CHANGED": indicates that the finding was present and + matched the given filter at the start of + compare_duration, but changed its state at read_time. + - "UNCHANGED": indicates that the finding was present and + matched the given filter at the start of compare_duration + and did not change state at read_time. + - "ADDED": indicates that the finding did not match the + given filter or was not present at the start of + compare_duration, but was present at read_time. + - "REMOVED": indicates that the finding was present and + matched the filter at the start of compare_duration, but + did not match the filter at read_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all findings present at read_time. + + If this field is set then ``state_change`` must be a + specified field in ``group_by``. + page_token (str): + The value returned by the last ``GroupFindingsResponse``; + indicates that this is a continuation of a prior + ``GroupFindings`` call, and that the system should return + the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field(proto.STRING, number=1) + + filter = proto.Field(proto.STRING, number=2) + + group_by = proto.Field(proto.STRING, number=3) + + read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) + + compare_duration = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) + + page_token = proto.Field(proto.STRING, number=7) + + page_size = proto.Field(proto.INT32, number=8) + + +class GroupFindingsResponse(proto.Message): + r"""Response message for group by findings. + + Attributes: + group_by_results (Sequence[~.securitycenter_service.GroupResult]): + Group results. There exists an element for + each existing unique combination of + property/values. The element contains a count + for the number of times those specific + property/values appear. + read_time (~.timestamp.Timestamp): + Time used for executing the groupBy request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of results matching the + query. + """ + + @property + def raw_page(self): + return self + + group_by_results = proto.RepeatedField( + proto.MESSAGE, number=1, message="GroupResult", + ) + + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + next_page_token = proto.Field(proto.STRING, number=3) + + total_size = proto.Field(proto.INT32, number=4) + + +class GroupResult(proto.Message): + r"""Result containing the properties and count of a groupBy + request. + + Attributes: + properties (Sequence[~.securitycenter_service.GroupResult.PropertiesEntry]): + Properties matching the groupBy fields in the + request. + count (int): + Total count of resources for the given + properties. + """ + + properties = proto.MapField( + proto.STRING, proto.MESSAGE, number=1, message=struct.Value, + ) + + count = proto.Field(proto.INT64, number=2) + + +class ListNotificationConfigsRequest(proto.Message): + r"""Request message for listing notification configs. + + Attributes: + parent (str): + Required. Name of the organization to list notification + configs. Its format is "organizations/[organization_id]". + page_token (str): + The value returned by the last + ``ListNotificationConfigsResponse``; indicates that this is + a continuation of a prior ``ListNotificationConfigs`` call, + and that the system should return the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_token = proto.Field(proto.STRING, number=2) + + page_size = proto.Field(proto.INT32, number=3) + + +class ListNotificationConfigsResponse(proto.Message): + r"""Response message for listing notification configs. + + Attributes: + notification_configs (Sequence[~.gcs_notification_config.NotificationConfig]): + Notification configs belonging to the + requested parent. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + notification_configs = proto.RepeatedField( + proto.MESSAGE, number=1, message=gcs_notification_config.NotificationConfig, + ) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class ListSourcesRequest(proto.Message): + r"""Request message for listing sources. + + Attributes: + parent (str): + Required. Resource name of the parent of sources to list. + Its format should be "organizations/[organization_id]". + page_token (str): + The value returned by the last ``ListSourcesResponse``; + indicates that this is a continuation of a prior + ``ListSources`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_token = proto.Field(proto.STRING, number=2) + + page_size = proto.Field(proto.INT32, number=7) + + +class ListSourcesResponse(proto.Message): + r"""Response message for listing sources. + + Attributes: + sources (Sequence[~.gcs_source.Source]): + Sources belonging to the requested parent. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + sources = proto.RepeatedField(proto.MESSAGE, number=1, message=gcs_source.Source,) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class ListAssetsRequest(proto.Message): + r"""Request message for listing assets. + + Attributes: + parent (str): + Required. Name of the organization assets should belong to. + Its format is "organizations/[organization_id]". + filter (str): + Expression that defines the filter to apply across assets. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the Asset + resource. Examples include: + + - name + - security_center_properties.resource_name + - resource_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following are the allowed field and operator + combinations: + + - name: ``=`` + + - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``update_time = "2019-06-10T16:07:18-07:00"`` + ``update_time = 1560208038000`` + + - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``create_time = "2019-06-10T16:07:18-07:00"`` + ``create_time = 1560208038000`` + + - iam_policy.policy_blob: ``=``, ``:`` + + - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, + ``<=`` + + - security_marks.marks: ``=``, ``:`` + + - security_center_properties.resource_name: ``=``, ``:`` + + - security_center_properties.resource_display_name: ``=``, + ``:`` + + - security_center_properties.resource_type: ``=``, ``:`` + + - security_center_properties.resource_parent: ``=``, ``:`` + + - security_center_properties.resource_parent_display_name: + ``=``, ``:`` + + - security_center_properties.resource_project: ``=``, ``:`` + + - security_center_properties.resource_project_display_name: + ``=``, ``:`` + + - security_center_properties.resource_owners: ``=``, ``:`` + + For example, ``resource_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based on a + property existing: ``resource_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-resource_properties.my_property : ""`` + order_by (str): + Expression that defines what fields and order to use for + sorting. The string value should follow SQL syntax: comma + separated list of fields. For example: + "name,resource_properties.a_property". The default sorting + order is ascending. To specify descending order for a field, + a suffix " desc" should be appended to the field name. For + example: "name desc,resource_properties.a_property". + Redundant space characters in the syntax are insignificant. + "name desc,resource_properties.a_property" and " name desc , + resource_properties.a_property " are equivalent. + + The following fields are supported: name update_time + resource_properties security_marks.marks + security_center_properties.resource_name + security_center_properties.resource_display_name + security_center_properties.resource_parent + security_center_properties.resource_parent_display_name + security_center_properties.resource_project + security_center_properties.resource_project_display_name + security_center_properties.resource_type + read_time (~.timestamp.Timestamp): + Time used as a reference point when filtering + assets. The filter is limited to assets existing + at the supplied time and their values are those + at that specific time. Absence of this field + will default to the API's version of NOW. + compare_duration (~.duration.Duration): + When compare_duration is set, the ListAssetsResult's + "state_change" attribute is updated to indicate whether the + asset was added, removed, or remained present during the + compare_duration period of time that precedes the read_time. + This is the time between (read_time - compare_duration) and + read_time. + + The state_change value is derived based on the presence of + the asset at the two points in time. Intermediate state + changes between the two times don't affect the result. For + example, the results aren't affected if the asset is removed + and re-created again. + + Possible "state_change" values when compare_duration is + specified: + + - "ADDED": indicates that the asset was not present at the + start of compare_duration, but present at read_time. + - "REMOVED": indicates that the asset was present at the + start of compare_duration, but not present at read_time. + - "ACTIVE": indicates that the asset was present at both + the start and the end of the time period defined by + compare_duration and read_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all assets present at read_time. + field_mask (~.gp_field_mask.FieldMask): + Optional. A field mask to specify the + ListAssetsResult fields to be listed in the + response. An empty field mask will list all + fields. + page_token (str): + The value returned by the last ``ListAssetsResponse``; + indicates that this is a continuation of a prior + ``ListAssets`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field(proto.STRING, number=1) + + filter = proto.Field(proto.STRING, number=2) + + order_by = proto.Field(proto.STRING, number=3) + + read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) + + compare_duration = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) + + field_mask = proto.Field(proto.MESSAGE, number=7, message=gp_field_mask.FieldMask,) + + page_token = proto.Field(proto.STRING, number=8) + + page_size = proto.Field(proto.INT32, number=9) + + +class ListAssetsResponse(proto.Message): + r"""Response message for listing assets. + + Attributes: + list_assets_results (Sequence[~.securitycenter_service.ListAssetsResponse.ListAssetsResult]): + Assets matching the list request. + read_time (~.timestamp.Timestamp): + Time used for executing the list request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of assets matching the + query. + """ + + class ListAssetsResult(proto.Message): + r"""Result containing the Asset and its State. + + Attributes: + asset (~.gcs_asset.Asset): + Asset matching the search request. + state_change (~.securitycenter_service.ListAssetsResponse.ListAssetsResult.StateChange): + State change of the asset between the points + in time. + """ + + class StateChange(proto.Enum): + r"""The change in state of the asset. + + When querying across two points in time this describes the change + between the two points: ADDED, REMOVED, or ACTIVE. If there was no + compare_duration supplied in the request the state change will be: + UNUSED + """ + UNUSED = 0 + ADDED = 1 + REMOVED = 2 + ACTIVE = 3 + + asset = proto.Field(proto.MESSAGE, number=1, message=gcs_asset.Asset,) + + state_change = proto.Field( + proto.ENUM, + number=2, + enum="ListAssetsResponse.ListAssetsResult.StateChange", + ) + + @property + def raw_page(self): + return self + + list_assets_results = proto.RepeatedField( + proto.MESSAGE, number=1, message=ListAssetsResult, + ) + + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + next_page_token = proto.Field(proto.STRING, number=3) + + total_size = proto.Field(proto.INT32, number=4) + + +class ListFindingsRequest(proto.Message): + r"""Request message for listing findings. + + Attributes: + parent (str): + Required. Name of the source the findings belong to. Its + format is + "organizations/[organization_id]/sources/[source_id]". To + list across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/- + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - source_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + name: ``=`` parent: ``=``, ``:`` resource_name: ``=``, ``:`` + state: ``=``, ``:`` category: ``=``, ``:`` external_uri: + ``=``, ``:`` event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an RFC3339 + string. Examples: + ``event_time = "2019-06-10T16:07:18-07:00"`` + ``event_time = 1560208038000`` + + security_marks.marks: ``=``, ``:`` source_properties: ``=``, + ``:``, ``>``, ``<``, ``>=``, ``<=`` + + For example, ``source_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based on a + property existing: ``source_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-source_properties.my_property : ""`` + order_by (str): + Expression that defines what fields and order to use for + sorting. The string value should follow SQL syntax: comma + separated list of fields. For example: + "name,resource_properties.a_property". The default sorting + order is ascending. To specify descending order for a field, + a suffix " desc" should be appended to the field name. For + example: "name desc,source_properties.a_property". Redundant + space characters in the syntax are insignificant. "name + desc,source_properties.a_property" and " name desc , + source_properties.a_property " are equivalent. + + The following fields are supported: name parent state + category resource_name event_time source_properties + security_marks.marks + read_time (~.timestamp.Timestamp): + Time used as a reference point when filtering + findings. The filter is limited to findings + existing at the supplied time and their values + are those at that specific time. Absence of this + field will default to the API's version of NOW. + compare_duration (~.duration.Duration): + When compare_duration is set, the ListFindingsResult's + "state_change" attribute is updated to indicate whether the + finding had its state changed, the finding's state remained + unchanged, or if the finding was added in any state during + the compare_duration period of time that precedes the + read_time. This is the time between (read_time - + compare_duration) and read_time. + + The state_change value is derived based on the presence and + state of the finding at the two points in time. Intermediate + state changes between the two times don't affect the result. + For example, the results aren't affected if the finding is + made inactive and then active again. + + Possible "state_change" values when compare_duration is + specified: + + - "CHANGED": indicates that the finding was present and + matched the given filter at the start of + compare_duration, but changed its state at read_time. + - "UNCHANGED": indicates that the finding was present and + matched the given filter at the start of compare_duration + and did not change state at read_time. + - "ADDED": indicates that the finding did not match the + given filter or was not present at the start of + compare_duration, but was present at read_time. + - "REMOVED": indicates that the finding was present and + matched the filter at the start of compare_duration, but + did not match the filter at read_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all findings present at read_time. + field_mask (~.gp_field_mask.FieldMask): + Optional. A field mask to specify the Finding + fields to be listed in the response. An empty + field mask will list all fields. + page_token (str): + The value returned by the last ``ListFindingsResponse``; + indicates that this is a continuation of a prior + ``ListFindings`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field(proto.STRING, number=1) + + filter = proto.Field(proto.STRING, number=2) + + order_by = proto.Field(proto.STRING, number=3) + + read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) + + compare_duration = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) + + field_mask = proto.Field(proto.MESSAGE, number=7, message=gp_field_mask.FieldMask,) + + page_token = proto.Field(proto.STRING, number=8) + + page_size = proto.Field(proto.INT32, number=9) + + +class ListFindingsResponse(proto.Message): + r"""Response message for listing findings. + + Attributes: + list_findings_results (Sequence[~.securitycenter_service.ListFindingsResponse.ListFindingsResult]): + Findings matching the list request. + read_time (~.timestamp.Timestamp): + Time used for executing the list request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of findings matching the + query. + """ + + class ListFindingsResult(proto.Message): + r"""Result containing the Finding and its StateChange. + + Attributes: + finding (~.gcs_finding.Finding): + Finding matching the search request. + state_change (~.securitycenter_service.ListFindingsResponse.ListFindingsResult.StateChange): + State change of the finding between the + points in time. + resource (~.securitycenter_service.ListFindingsResponse.ListFindingsResult.Resource): + Output only. Resource that is associated with + this finding. + """ + + class StateChange(proto.Enum): + r"""The change in state of the finding. + + When querying across two points in time this describes the change in + the finding between the two points: CHANGED, UNCHANGED, ADDED, or + REMOVED. Findings can not be deleted, so REMOVED implies that the + finding at timestamp does not match the filter specified, but it did + at timestamp - compare_duration. If there was no compare_duration + supplied in the request the state change will be: UNUSED + """ + UNUSED = 0 + CHANGED = 1 + UNCHANGED = 2 + ADDED = 3 + REMOVED = 4 + + class Resource(proto.Message): + r"""Information related to the Google Cloud resource that is + associated with this finding. + + Attributes: + name (str): + The full resource name of the resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + project_name (str): + The full resource name of project that the + resource belongs to. + project_display_name (str): + The human readable name of project that the + resource belongs to. + parent_name (str): + The full resource name of resource's parent. + parent_display_name (str): + The human readable name of resource's parent. + """ + + name = proto.Field(proto.STRING, number=1) + + project_name = proto.Field(proto.STRING, number=2) + + project_display_name = proto.Field(proto.STRING, number=3) + + parent_name = proto.Field(proto.STRING, number=4) + + parent_display_name = proto.Field(proto.STRING, number=5) + + finding = proto.Field(proto.MESSAGE, number=1, message=gcs_finding.Finding,) + + state_change = proto.Field( + proto.ENUM, + number=2, + enum="ListFindingsResponse.ListFindingsResult.StateChange", + ) + + resource = proto.Field( + proto.MESSAGE, + number=3, + message="ListFindingsResponse.ListFindingsResult.Resource", + ) + + @property + def raw_page(self): + return self + + list_findings_results = proto.RepeatedField( + proto.MESSAGE, number=1, message=ListFindingsResult, + ) + + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + next_page_token = proto.Field(proto.STRING, number=3) + + total_size = proto.Field(proto.INT32, number=4) + + +class SetFindingStateRequest(proto.Message): + r"""Request message for updating a finding's state. + + Attributes: + name (str): + Required. The relative resource name of the finding. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + state (~.gcs_finding.Finding.State): + Required. The desired State of the finding. + start_time (~.timestamp.Timestamp): + Required. The time at which the updated state + takes effect. + """ + + name = proto.Field(proto.STRING, number=1) + + state = proto.Field(proto.ENUM, number=2, enum=gcs_finding.Finding.State,) + + start_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + + +class RunAssetDiscoveryRequest(proto.Message): + r"""Request message for running asset discovery for an + organization. + + Attributes: + parent (str): + Required. Name of the organization to run asset discovery + for. Its format is "organizations/[organization_id]". + """ + + parent = proto.Field(proto.STRING, number=1) + + +class UpdateFindingRequest(proto.Message): + r"""Request message for updating or creating a finding. + + Attributes: + finding (~.gcs_finding.Finding): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the name + must be alphanumeric and less than or equal to 32 characters + and greater than 0 characters in length. + update_mask (~.gp_field_mask.FieldMask): + The FieldMask to use when updating the finding resource. + This field should not be specified when creating a finding. + + When updating a finding, an empty mask is treated as + updating all mutable fields and replacing source_properties. + Individual source_properties can be added/updated by using + "source_properties." in the field mask. + """ + + finding = proto.Field(proto.MESSAGE, number=1, message=gcs_finding.Finding,) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + + +class UpdateNotificationConfigRequest(proto.Message): + r"""Request message for updating a notification config. + + Attributes: + notification_config (~.gcs_notification_config.NotificationConfig): + Required. The notification config to update. + update_mask (~.gp_field_mask.FieldMask): + The FieldMask to use when updating the + notification config. + If empty all mutable fields will be updated. + """ + + notification_config = proto.Field( + proto.MESSAGE, number=1, message=gcs_notification_config.NotificationConfig, + ) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + + +class UpdateOrganizationSettingsRequest(proto.Message): + r"""Request message for updating an organization's settings. + + Attributes: + organization_settings (~.gcs_organization_settings.OrganizationSettings): + Required. The organization settings resource + to update. + update_mask (~.gp_field_mask.FieldMask): + The FieldMask to use when updating the + settings resource. + If empty all mutable fields will be updated. + """ + + organization_settings = proto.Field( + proto.MESSAGE, number=1, message=gcs_organization_settings.OrganizationSettings, + ) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + + +class UpdateSourceRequest(proto.Message): + r"""Request message for updating a source. + + Attributes: + source (~.gcs_source.Source): + Required. The source resource to update. + update_mask (~.gp_field_mask.FieldMask): + The FieldMask to use when updating the source + resource. + If empty all mutable fields will be updated. + """ + + source = proto.Field(proto.MESSAGE, number=1, message=gcs_source.Source,) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + + +class UpdateSecurityMarksRequest(proto.Message): + r"""Request message for updating a SecurityMarks resource. + + Attributes: + security_marks (~.gcs_security_marks.SecurityMarks): + Required. The security marks resource to + update. + update_mask (~.gp_field_mask.FieldMask): + The FieldMask to use when updating the security marks + resource. + + The field mask must not contain duplicate fields. If empty + or set to "marks", all marks will be replaced. Individual + marks can be updated using "marks.". + start_time (~.timestamp.Timestamp): + The time at which the updated SecurityMarks + take effect. If not set uses current server + time. Updates will be applied to the + SecurityMarks that are active immediately + preceding this time. + """ + + security_marks = proto.Field( + proto.MESSAGE, number=1, message=gcs_security_marks.SecurityMarks, + ) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + + start_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/source.py b/google/cloud/securitycenter_v1/types/source.py new file mode 100644 index 00000000..ce412d1c --- /dev/null +++ b/google/cloud/securitycenter_v1/types/source.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1", manifest={"Source",}, +) + + +class Source(proto.Message): + r"""Security Command Center finding source. A finding source + is an entity or a mechanism that can produce a finding. A source + is like a container of findings that come from the same scanner, + logger, monitor, and other tools. + + Attributes: + name (str): + The relative resource name of this source. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}". + display_name (str): + The source's display name. + A source's display name must be unique amongst + its siblings, for example, two sources with the + same parent can't share the same display name. + The display name must have a length between 1 + and 64 characters (inclusive). + description (str): + The description of the source (max of 1024 + characters). Example: + "Web Security Scanner is a web security scanner + for common vulnerabilities in App Engine + applications. It can automatically scan and + detect four common vulnerabilities, including + cross-site-scripting (XSS), Flash injection, + mixed content (HTTP in HTTPS), and outdated or + insecure libraries.". + """ + + name = proto.Field(proto.STRING, number=1) + + display_name = proto.Field(proto.STRING, number=2) + + description = proto.Field(proto.STRING, number=3) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1beta1/__init__.py b/google/cloud/securitycenter_v1beta1/__init__.py index 6944ab92..55c3ce49 100644 --- a/google/cloud/securitycenter_v1beta1/__init__.py +++ b/google/cloud/securitycenter_v1beta1/__init__.py @@ -1,45 +1,77 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 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 +# 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 absolute_import -import sys -import warnings - -from google.cloud.securitycenter_v1beta1 import types -from google.cloud.securitycenter_v1beta1.gapic import enums -from google.cloud.securitycenter_v1beta1.gapic import security_center_client - - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7. " - "More details about Python 2 support for Google Cloud Client Libraries " - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) - - -class SecurityCenterClient(security_center_client.SecurityCenterClient): - __doc__ = security_center_client.SecurityCenterClient.__doc__ - enums = enums +from .services.security_center import SecurityCenterClient +from .types.asset import Asset +from .types.finding import Finding +from .types.organization_settings import OrganizationSettings +from .types.run_asset_discovery_response import RunAssetDiscoveryResponse +from .types.security_marks import SecurityMarks +from .types.securitycenter_service import CreateFindingRequest +from .types.securitycenter_service import CreateSourceRequest +from .types.securitycenter_service import GetOrganizationSettingsRequest +from .types.securitycenter_service import GetSourceRequest +from .types.securitycenter_service import GroupAssetsRequest +from .types.securitycenter_service import GroupAssetsResponse +from .types.securitycenter_service import GroupFindingsRequest +from .types.securitycenter_service import GroupFindingsResponse +from .types.securitycenter_service import GroupResult +from .types.securitycenter_service import ListAssetsRequest +from .types.securitycenter_service import ListAssetsResponse +from .types.securitycenter_service import ListFindingsRequest +from .types.securitycenter_service import ListFindingsResponse +from .types.securitycenter_service import ListSourcesRequest +from .types.securitycenter_service import ListSourcesResponse +from .types.securitycenter_service import RunAssetDiscoveryRequest +from .types.securitycenter_service import SetFindingStateRequest +from .types.securitycenter_service import UpdateFindingRequest +from .types.securitycenter_service import UpdateOrganizationSettingsRequest +from .types.securitycenter_service import UpdateSecurityMarksRequest +from .types.securitycenter_service import UpdateSourceRequest +from .types.source import Source __all__ = ( - "enums", - "types", + "Asset", + "CreateFindingRequest", + "CreateSourceRequest", + "Finding", + "GetOrganizationSettingsRequest", + "GetSourceRequest", + "GroupAssetsRequest", + "GroupAssetsResponse", + "GroupFindingsRequest", + "GroupFindingsResponse", + "GroupResult", + "ListAssetsRequest", + "ListAssetsResponse", + "ListFindingsRequest", + "ListFindingsResponse", + "ListSourcesRequest", + "ListSourcesResponse", + "OrganizationSettings", + "RunAssetDiscoveryRequest", + "RunAssetDiscoveryResponse", + "SecurityMarks", + "SetFindingStateRequest", + "Source", + "UpdateFindingRequest", + "UpdateOrganizationSettingsRequest", + "UpdateSecurityMarksRequest", + "UpdateSourceRequest", "SecurityCenterClient", ) diff --git a/google/cloud/securitycenter_v1beta1/gapic/security_center_client.py b/google/cloud/securitycenter_v1beta1/gapic/security_center_client.py index bc638425..72660006 100644 --- a/google/cloud/securitycenter_v1beta1/gapic/security_center_client.py +++ b/google/cloud/securitycenter_v1beta1/gapic/security_center_client.py @@ -89,6 +89,15 @@ def from_service_account_file(cls, filename, *args, **kwargs): from_service_account_json = from_service_account_file + @classmethod + def asset_security_marks_path(cls, organization, asset): + """Return a fully-qualified asset_security_marks string.""" + return google.api_core.path_template.expand( + "organizations/{organization}/assets/{asset}/securityMarks", + organization=organization, + asset=asset, + ) + @classmethod def finding_path(cls, organization, source, finding): """Return a fully-qualified finding string.""" @@ -99,6 +108,16 @@ def finding_path(cls, organization, source, finding): finding=finding, ) + @classmethod + def finding_security_marks_path(cls, organization, source, finding): + """Return a fully-qualified finding_security_marks string.""" + return google.api_core.path_template.expand( + "organizations/{organization}/sources/{source}/findings/{finding}/securityMarks", + organization=organization, + source=source, + finding=finding, + ) + @classmethod def organization_path(cls, organization): """Return a fully-qualified organization string.""" @@ -114,15 +133,6 @@ def organization_settings_path(cls, organization): organization=organization, ) - @classmethod - def security_marks_path(cls, organization, asset): - """Return a fully-qualified security_marks string.""" - return google.api_core.path_template.expand( - "organizations/{organization}/assets/{asset}/securityMarks", - organization=organization, - asset=asset, - ) - @classmethod def source_path(cls, organization, source): """Return a fully-qualified source string.""" @@ -431,8 +441,7 @@ def get_iam_policy( >>> >>> client = securitycenter_v1beta1.SecurityCenterClient() >>> - >>> # TODO: Initialize `resource`: - >>> resource = '' + >>> resource = client.source_path('[ORGANIZATION]', '[SOURCE]') >>> >>> response = client.get_iam_policy(resource) @@ -1638,8 +1647,7 @@ def set_iam_policy( >>> >>> client = securitycenter_v1beta1.SecurityCenterClient() >>> - >>> # TODO: Initialize `resource`: - >>> resource = '' + >>> resource = client.source_path('[ORGANIZATION]', '[SOURCE]') >>> >>> # TODO: Initialize `policy`: >>> policy = {} @@ -1720,8 +1728,7 @@ def test_iam_permissions( >>> >>> client = securitycenter_v1beta1.SecurityCenterClient() >>> - >>> # TODO: Initialize `resource`: - >>> resource = '' + >>> resource = client.source_path('[ORGANIZATION]', '[SOURCE]') >>> >>> # TODO: Initialize `permissions`: >>> permissions = [] diff --git a/google/cloud/securitycenter_v1beta1/gapic/security_center_client_config.py b/google/cloud/securitycenter_v1beta1/gapic/security_center_client_config.py index 6d6b421b..9b5c01a9 100644 --- a/google/cloud/securitycenter_v1beta1/gapic/security_center_client_config.py +++ b/google/cloud/securitycenter_v1beta1/gapic/security_center_client_config.py @@ -2,149 +2,110 @@ "interfaces": { "google.cloud.securitycenter.v1beta1.SecurityCenter": { "retry_codes": { - "retry_policy_1_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "no_retry_2_codes": [], - "no_retry_codes": [], - "retry_policy_2_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "no_retry_1_codes": [], + "idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], + "non_idempotent": [], }, "retry_params": { - "retry_policy_1_params": { + "default": { "initial_retry_delay_millis": 100, "retry_delay_multiplier": 1.3, "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 60000, + "initial_rpc_timeout_millis": 20000, "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 60000, - }, - "retry_policy_2_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 480000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 480000, - "total_timeout_millis": 480000, - }, - "no_retry_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 0, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 0, - "total_timeout_millis": 0, - }, - "no_retry_1_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 60000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 60000, - }, - "no_retry_2_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 480000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 480000, - "total_timeout_millis": 480000, - }, + "max_rpc_timeout_millis": 20000, + "total_timeout_millis": 600000, + } }, "methods": { "CreateSource": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "CreateFinding": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "GetIamPolicy": { "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", + "retry_codes_name": "idempotent", + "retry_params_name": "default", }, "GetOrganizationSettings": { "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", + "retry_codes_name": "idempotent", + "retry_params_name": "default", }, "GetSource": { "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", + "retry_codes_name": "idempotent", + "retry_params_name": "default", }, "GroupAssets": { - "timeout_millis": 480000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default", }, "GroupFindings": { - "timeout_millis": 480000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default", }, "ListAssets": { - "timeout_millis": 480000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default", }, "ListFindings": { - "timeout_millis": 480000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default", }, "ListSources": { "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", + "retry_codes_name": "idempotent", + "retry_params_name": "default", }, "RunAssetDiscovery": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "SetFindingState": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "SetIamPolicy": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "TestIamPermissions": { "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", + "retry_codes_name": "idempotent", + "retry_params_name": "default", }, "UpdateFinding": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "UpdateOrganizationSettings": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "UpdateSource": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "UpdateSecurityMarks": { - "timeout_millis": 480000, - "retry_codes_name": "no_retry_2_codes", - "retry_params_name": "no_retry_2_params", + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, }, } diff --git a/google/cloud/securitycenter_v1beta1/proto/asset_pb2.py b/google/cloud/securitycenter_v1beta1/proto/asset_pb2.py index cf7ceb98..e1e488ee 100644 --- a/google/cloud/securitycenter_v1beta1/proto/asset_pb2.py +++ b/google/cloud/securitycenter_v1beta1/proto/asset_pb2.py @@ -13,7 +13,6 @@ from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 -from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 from google.cloud.securitycenter_v1beta1.proto import ( security_marks_pb2 as google_dot_cloud_dot_securitycenter__v1beta1_dot_proto_dot_security__marks__pb2, ) @@ -28,10 +27,9 @@ syntax="proto3", serialized_options=b"\n'com.google.cloud.securitycenter.v1beta1P\001ZQgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1;securitycenter", create_key=_descriptor._internal_create_key, - serialized_pb=b"\n5google/cloud/securitycenter_v1beta1/proto/asset.proto\x12#google.cloud.securitycenter.v1beta1\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a>google/cloud/securitycenter_v1beta1/proto/security_marks.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1cgoogle/api/annotations.proto\"\xd3\x05\n\x05\x41sset\x12\x0c\n\x04name\x18\x01 \x01(\t\x12g\n\x1asecurity_center_properties\x18\x02 \x01(\x0b\x32\x43.google.cloud.securitycenter.v1beta1.Asset.SecurityCenterProperties\x12_\n\x13resource_properties\x18\x07 \x03(\x0b\x32\x42.google.cloud.securitycenter.v1beta1.Asset.ResourcePropertiesEntry\x12J\n\x0esecurity_marks\x18\x08 \x01(\x0b\x32\x32.google.cloud.securitycenter.v1beta1.SecurityMarks\x12/\n\x0b\x63reate_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0bupdate_time\x18\n \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x1a\x99\x01\n\x18SecurityCenterProperties\x12\x1a\n\rresource_name\x18\x01 \x01(\tB\x03\xe0\x41\x05\x12\x15\n\rresource_type\x18\x02 \x01(\t\x12\x17\n\x0fresource_parent\x18\x03 \x01(\t\x12\x18\n\x10resource_project\x18\x04 \x01(\t\x12\x17\n\x0fresource_owners\x18\x05 \x03(\t\x1aQ\n\x17ResourcePropertiesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12%\n\x05value\x18\x02 \x01(\x0b\x32\x16.google.protobuf.Value:\x02\x38\x01:U\xea\x41R\n#securitycenter.googleapis.com/Asset\x12+organizations/{organization}/assets/{asset}B~\n'com.google.cloud.securitycenter.v1beta1P\x01ZQgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1;securitycenterb\x06proto3", + serialized_pb=b"\n5google/cloud/securitycenter_v1beta1/proto/asset.proto\x12#google.cloud.securitycenter.v1beta1\x1a\x1fgoogle/api/field_behavior.proto\x1a>google/cloud/securitycenter_v1beta1/proto/security_marks.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1cgoogle/api/annotations.proto\"\xfc\x04\n\x05\x41sset\x12\x0c\n\x04name\x18\x01 \x01(\t\x12g\n\x1asecurity_center_properties\x18\x02 \x01(\x0b\x32\x43.google.cloud.securitycenter.v1beta1.Asset.SecurityCenterProperties\x12_\n\x13resource_properties\x18\x07 \x03(\x0b\x32\x42.google.cloud.securitycenter.v1beta1.Asset.ResourcePropertiesEntry\x12J\n\x0esecurity_marks\x18\x08 \x01(\x0b\x32\x32.google.cloud.securitycenter.v1beta1.SecurityMarks\x12/\n\x0b\x63reate_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0bupdate_time\x18\n \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x1a\x99\x01\n\x18SecurityCenterProperties\x12\x1a\n\rresource_name\x18\x01 \x01(\tB\x03\xe0\x41\x05\x12\x15\n\rresource_type\x18\x02 \x01(\t\x12\x17\n\x0fresource_parent\x18\x03 \x01(\t\x12\x18\n\x10resource_project\x18\x04 \x01(\t\x12\x17\n\x0fresource_owners\x18\x05 \x03(\t\x1aQ\n\x17ResourcePropertiesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12%\n\x05value\x18\x02 \x01(\x0b\x32\x16.google.protobuf.Value:\x02\x38\x01\x42~\n'com.google.cloud.securitycenter.v1beta1P\x01ZQgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1;securitycenterb\x06proto3", dependencies=[ google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, - google_dot_api_dot_resource__pb2.DESCRIPTOR, google_dot_cloud_dot_securitycenter__v1beta1_dot_proto_dot_security__marks__pb2.DESCRIPTOR, google_dot_protobuf_dot_struct__pb2.DESCRIPTOR, google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, @@ -152,8 +150,8 @@ syntax="proto3", extension_ranges=[], oneofs=[], - serialized_start=712, - serialized_end=865, + serialized_start=685, + serialized_end=838, ) _ASSET_RESOURCEPROPERTIESENTRY = _descriptor.Descriptor( @@ -211,8 +209,8 @@ syntax="proto3", extension_ranges=[], oneofs=[], - serialized_start=867, - serialized_end=948, + serialized_start=840, + serialized_end=921, ) _ASSET = _descriptor.Descriptor( @@ -341,13 +339,13 @@ extensions=[], nested_types=[_ASSET_SECURITYCENTERPROPERTIES, _ASSET_RESOURCEPROPERTIESENTRY,], enum_types=[], - serialized_options=b"\352AR\n#securitycenter.googleapis.com/Asset\022+organizations/{organization}/assets/{asset}", + serialized_options=None, is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], - serialized_start=312, - serialized_end=1035, + serialized_start=285, + serialized_end=921, ) _ASSET_SECURITYCENTERPROPERTIES.containing_type = _ASSET @@ -385,21 +383,20 @@ { "DESCRIPTOR": _ASSET_SECURITYCENTERPROPERTIES, "__module__": "google.cloud.securitycenter_v1beta1.proto.asset_pb2", - "__doc__": """Security Command Center managed properties. These properties are - managed by Security Command Center and cannot be modified by the user. + "__doc__": """Cloud SCC managed properties. These properties are managed by Cloud + SCC and cannot be modified by the user. Attributes: resource_name: - Immutable. The full resource name of the Google Cloud resource - this asset represents. This field is immutable after create - time. See: https://cloud.google.com/apis/design/resource_names - #full_resource_name + Immutable. The full resource name of the GCP resource this + asset represents. This field is immutable after create time. + See: https://cloud.google.com/apis/design/resource_names#full_ + resource_name resource_type: - The type of the Google Cloud resource. Examples include: - APPLICATION, PROJECT, and ORGANIZATION. This is a case - insensitive field defined by Security Command Center and/or - the producer of the resource and is immutable after create - time. + The type of the GCP resource. Examples include: APPLICATION, + PROJECT, and ORGANIZATION. This is a case insensitive field + defined by Cloud SCC and/or the producer of the resource and + is immutable after create time. resource_parent: The full resource name of the immediate parent of the resource. See: https://cloud.google.com/apis/design/resource_n @@ -425,11 +422,11 @@ ), "DESCRIPTOR": _ASSET, "__module__": "google.cloud.securitycenter_v1beta1.proto.asset_pb2", - "__doc__": """Security Command Center representation of a Google Cloud resource. - The Asset is a Security Command Center resource that captures - information about a single Google Cloud resource. All modifications to - an Asset are only within the context of Security Command Center and - don’t affect the referenced Google Cloud resource. + "__doc__": """Cloud Security Command Center’s (Cloud SCC) representation of a Google + Cloud Platform (GCP) resource. The Asset is a Cloud SCC resource that + captures information about a single GCP resource. All modifications to + an Asset are only within the context of Cloud SCC and don’t affect the + referenced GCP resource. Attributes: name: @@ -437,23 +434,21 @@ oogle.com/apis/design/resource_names#relative_resource_name Example: “organizations/{organization_id}/assets/{asset_id}”. security_center_properties: - Security Command Center managed properties. These properties - are managed by Security Command Center and cannot be modified - by the user. + Cloud SCC managed properties. These properties are managed by + Cloud SCC and cannot be modified by the user. resource_properties: Resource managed properties. These properties are managed and - defined by the Google Cloud resource and cannot be modified by - the user. + defined by the GCP resource and cannot be modified by the + user. security_marks: User specified security marks. These marks are entirely managed by the user and come from the SecurityMarks resource that belongs to the asset. create_time: - The time at which the asset was created in Security Command - Center. + The time at which the asset was created in Cloud SCC. update_time: The time at which the asset was last updated, added, or - deleted in Security Command Center. + deleted in Cloud SCC. """, # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.Asset) }, @@ -466,5 +461,4 @@ DESCRIPTOR._options = None _ASSET_SECURITYCENTERPROPERTIES.fields_by_name["resource_name"]._options = None _ASSET_RESOURCEPROPERTIESENTRY._options = None -_ASSET._options = None # @@protoc_insertion_point(module_scope) diff --git a/google/cloud/securitycenter_v1beta1/proto/finding_pb2.py b/google/cloud/securitycenter_v1beta1/proto/finding_pb2.py index f2620c16..0c7b8e81 100644 --- a/google/cloud/securitycenter_v1beta1/proto/finding_pb2.py +++ b/google/cloud/securitycenter_v1beta1/proto/finding_pb2.py @@ -388,9 +388,9 @@ ), "DESCRIPTOR": _FINDING, "__module__": "google.cloud.securitycenter_v1beta1.proto.finding_pb2", - "__doc__": """Security Command Center finding. A finding is a record of assessment - data (security, risk, health or privacy) ingested into Security - Command Center for presentation, notification, analysis, policy + "__doc__": """Cloud Security Command Center (Cloud SCC) finding. A finding is a + record of assessment data (security, risk, health or privacy) ingested + into Cloud SCC for presentation, notification, analysis, policy testing, and enforcement. For example, an XSS vulnerability in an App Engine application is a finding. @@ -407,10 +407,10 @@ after creation time. For example: “organizations/{organization_id}/sources/{source_id}” resource_name: - For findings on Google Cloud resources, the full resource name - of the Google Cloud resource this finding is for. See: https:/ - /cloud.google.com/apis/design/resource_names#full_resource_nam - e When the finding is for a non-Google Cloud resource, the + For findings on Google Cloud Platform (GCP) resources, the + full resource name of the GCP resource this finding is for. + See: https://cloud.google.com/apis/design/resource_names#full_ + resource_name When the finding is for a non-GCP resource, the resourceName can be a customer or partner defined string. This field is immutable after creation time. state: @@ -421,9 +421,9 @@ “XSS_FLASH_INJECTION” external_uri: The URI that, if available, points to a web page outside of - Security Command Center where additional information about the - finding can be found. This field is guaranteed to be either - empty or a well formed URL. + Cloud SCC where additional information about the finding can + be found. This field is guaranteed to be either empty or a + well formed URL. source_properties: Source specific properties. These properties are managed by the source that writes the finding. The key names in the @@ -440,8 +440,7 @@ the detector believes the firewall became open. The accuracy is determined by the detector. create_time: - The time at which the finding was created in Security Command - Center. + The time at which the finding was created in Cloud SCC. """, # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.Finding) }, diff --git a/google/cloud/securitycenter_v1beta1/proto/organization_settings_pb2.py b/google/cloud/securitycenter_v1beta1/proto/organization_settings_pb2.py index 1d6fdb84..779190be 100644 --- a/google/cloud/securitycenter_v1beta1/proto/organization_settings_pb2.py +++ b/google/cloud/securitycenter_v1beta1/proto/organization_settings_pb2.py @@ -243,8 +243,8 @@ ), "DESCRIPTOR": _ORGANIZATIONSETTINGS, "__module__": "google.cloud.securitycenter_v1beta1.proto.organization_settings_pb2", - "__doc__": """User specified settings that are attached to the Security Command - Center organization. + "__doc__": """User specified settings that are attached to the Cloud Security + Command Center (Cloud SCC) organization. Attributes: name: diff --git a/google/cloud/securitycenter_v1beta1/proto/security_marks_pb2.py b/google/cloud/securitycenter_v1beta1/proto/security_marks_pb2.py index 558b3e3a..a9cae49e 100644 --- a/google/cloud/securitycenter_v1beta1/proto/security_marks_pb2.py +++ b/google/cloud/securitycenter_v1beta1/proto/security_marks_pb2.py @@ -168,10 +168,10 @@ ), "DESCRIPTOR": _SECURITYMARKS, "__module__": "google.cloud.securitycenter_v1beta1.proto.security_marks_pb2", - "__doc__": """User specified security marks that are attached to the parent Security - Command Center resource. Security marks are scoped within a Security - Command Center organization – they can be modified and viewed by all - users who have proper permissions on the organization. + "__doc__": """User specified security marks that are attached to the parent Cloud + Security Command Center (Cloud SCC) resource. Security marks are + scoped within a Cloud SCC organization – they can be modified and + viewed by all users who have proper permissions on the organization. Attributes: name: diff --git a/google/cloud/securitycenter_v1beta1/proto/source_pb2.py b/google/cloud/securitycenter_v1beta1/proto/source_pb2.py index 886c0336..835fccd5 100644 --- a/google/cloud/securitycenter_v1beta1/proto/source_pb2.py +++ b/google/cloud/securitycenter_v1beta1/proto/source_pb2.py @@ -117,10 +117,10 @@ { "DESCRIPTOR": _SOURCE, "__module__": "google.cloud.securitycenter_v1beta1.proto.source_pb2", - "__doc__": """Security Command Center finding source. A finding source is an entity - or a mechanism that can produce a finding. A source is like a - container of findings that come from the same scanner, logger, - monitor, etc. + "__doc__": """Cloud Security Command Center’s (Cloud SCC) finding source. A finding + source is an entity or a mechanism that can produce a finding. A + source is like a container of findings that come from the same + scanner, logger, monitor, etc. Attributes: name: @@ -135,7 +135,7 @@ (inclusive). description: The description of the source (max of 1024 characters). - Example: “Web Security Scanner is a web security scanner for + Example: “Cloud Security Scanner is a web security scanner for common vulnerabilities in App Engine applications. It can automatically scan and detect four common vulnerabilities, including cross-site-scripting (XSS), Flash injection, mixed diff --git a/google/cloud/securitycenter_v1beta1/py.typed b/google/cloud/securitycenter_v1beta1/py.typed new file mode 100644 index 00000000..23a44fc7 --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-securitycenter package uses inline types. diff --git a/google/cloud/securitycenter_v1beta1/services/__init__.py b/google/cloud/securitycenter_v1beta1/services/__init__.py new file mode 100644 index 00000000..42ffdf2b --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/services/__init__.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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. +# diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/__init__.py b/google/cloud/securitycenter_v1beta1/services/security_center/__init__.py new file mode 100644 index 00000000..6250349b --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/services/security_center/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 SecurityCenterClient +from .async_client import SecurityCenterAsyncClient + +__all__ = ( + "SecurityCenterClient", + "SecurityCenterAsyncClient", +) diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py b/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py new file mode 100644 index 00000000..2be877e7 --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py @@ -0,0 +1,1801 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation +from google.api_core import operation_async +from google.cloud.securitycenter_v1beta1.services.security_center import pagers +from google.cloud.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import organization_settings +from google.cloud.securitycenter_v1beta1.types import ( + organization_settings as gcs_organization_settings, +) +from google.cloud.securitycenter_v1beta1.types import security_marks +from google.cloud.securitycenter_v1beta1.types import ( + security_marks as gcs_security_marks, +) +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + +from .transports.base import SecurityCenterTransport +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .client import SecurityCenterClient + + +class SecurityCenterAsyncClient: + """V1 Beta APIs for Security Center service.""" + + _client: SecurityCenterClient + + DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + + organization_settings_path = staticmethod( + SecurityCenterClient.organization_settings_path + ) + + finding_path = staticmethod(SecurityCenterClient.finding_path) + + source_path = staticmethod(SecurityCenterClient.source_path) + + security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + + from_service_account_file = SecurityCenterClient.from_service_account_file + from_service_account_json = from_service_account_file + + get_transport_class = functools.partial( + type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, SecurityCenterTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + ) -> None: + """Instantiate the security center 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. + transport (Union[str, ~.SecurityCenterTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = SecurityCenterClient( + credentials=credentials, transport=transport, client_options=client_options, + ) + + async def create_source( + self, + request: securitycenter_service.CreateSourceRequest = None, + *, + parent: str = None, + source: gcs_source.Source = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a source. + + Args: + request (:class:`~.securitycenter_service.CreateSourceRequest`): + The request object. Request message for creating a + source. + parent (:class:`str`): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (:class:`~.gcs_source.Source`): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + This corresponds to the ``source`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, source]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.CreateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_source, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def create_finding( + self, + request: securitycenter_service.CreateFindingRequest = None, + *, + parent: str = None, + finding_id: str = None, + finding: gcs_finding.Finding = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Args: + request (:class:`~.securitycenter_service.CreateFindingRequest`): + The request object. Request message for creating a + finding. + parent (:class:`str`): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + It must be alphanumeric and less than or + equal to 32 characters and greater than + 0 characters in length. + This corresponds to the ``finding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (:class:`~.gcs_finding.Finding`): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + This corresponds to the ``finding`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_finding.Finding: + Security Command Center finding. + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, finding_id, finding]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.CreateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if finding_id is not None: + request.finding_id = finding_id + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_finding, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_iam_policy( + self, + request: iam_policy.GetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Gets the access control policy on the specified + Source. + + Args: + request (:class:`~.iam_policy.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + This corresponds to the ``resource`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([resource]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.GetIamPolicyRequest(**request) + + elif not request: + request = iam_policy.GetIamPolicyRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_organization_settings( + self, + request: securitycenter_service.GetOrganizationSettingsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> organization_settings.OrganizationSettings: + r"""Gets the settings for an organization. + + Args: + request (:class:`~.securitycenter_service.GetOrganizationSettingsRequest`): + The request object. Request message for getting + organization settings. + name (:class:`str`): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + This corresponds to the ``name`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.organization_settings.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.GetOrganizationSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_organization_settings, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_source( + self, + request: securitycenter_service.GetSourceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Gets a source. + + Args: + request (:class:`~.securitycenter_service.GetSourceRequest`): + The request object. Request message for getting a + source. + name (:class:`str`): + Required. Relative resource name of the source. Its + format is + "organizations/[organization_id]/source/[source_id]". + This corresponds to the ``name`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.GetSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_source, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def group_assets( + self, + request: securitycenter_service.GroupAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupAssetsAsyncPager: + r"""Filters an organization's assets and groups them by + their specified properties. + + Args: + request (:class:`~.securitycenter_service.GroupAssetsRequest`): + The request object. Request message for grouping by + assets. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.GroupAssetsAsyncPager: + Response message for grouping by + assets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + + request = securitycenter_service.GroupAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.group_assets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.GroupAssetsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def group_findings( + self, + request: securitycenter_service.GroupFindingsRequest = None, + *, + parent: str = None, + group_by: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsAsyncPager: + r"""Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + Args: + request (:class:`~.securitycenter_service.GroupFindingsRequest`): + The request object. Request message for grouping by + findings. + parent (:class:`str`): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]". + To groupBy across all sources provide a source_id of + ``-``. For example: + organizations/{organization_id}/sources/- + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (:class:`str`): + Required. Expression that defines what assets fields to + use for grouping (including ``state``). The string value + should follow SQL syntax: comma separated list of + fields. For example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + This corresponds to the ``group_by`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.GroupFindingsAsyncPager: + Response message for group by + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, group_by]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.GroupFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.group_findings, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.GroupFindingsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_assets( + self, + request: securitycenter_service.ListAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsAsyncPager: + r"""Lists an organization's assets. + + Args: + request (:class:`~.securitycenter_service.ListAssetsRequest`): + The request object. Request message for listing assets. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListAssetsAsyncPager: + Response message for listing assets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + + request = securitycenter_service.ListAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_assets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAssetsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_findings( + self, + request: securitycenter_service.ListFindingsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFindingsAsyncPager: + r"""Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + Args: + request (:class:`~.securitycenter_service.ListFindingsRequest`): + The request object. Request message for listing + findings. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListFindingsAsyncPager: + Response message for listing + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + + request = securitycenter_service.ListFindingsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_findings, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListFindingsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_sources( + self, + request: securitycenter_service.ListSourcesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSourcesAsyncPager: + r"""Lists all sources belonging to an organization. + + Args: + request (:class:`~.securitycenter_service.ListSourcesRequest`): + The request object. Request message for listing sources. + parent (:class:`str`): + Required. Resource name of the parent of sources to + list. Its format should be + "organizations/[organization_id]". + This corresponds to the ``parent`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListSourcesAsyncPager: + Response message for listing sources. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.ListSourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_sources, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSourcesAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def run_asset_discovery( + self, + request: securitycenter_service.RunAssetDiscoveryRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Args: + request (:class:`~.securitycenter_service.RunAssetDiscoveryRequest`): + The request object. Request message for running asset + discovery for an organization. + parent (:class:`str`): + Required. Name of the organization to run asset + discovery for. Its format is + "organizations/[organization_id]". + This corresponds to the ``parent`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.empty.Empty``: A generic empty message that + you can re-use to avoid defining duplicated empty + messages in your APIs. A typical example is to use it as + the request or the response type of an API method. For + instance: + + :: + + service Foo { + rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); + } + + The JSON representation for ``Empty`` is empty JSON + object ``{}``. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.RunAssetDiscoveryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.run_asset_discovery, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + empty.Empty, + metadata_type=empty.Empty, + ) + + # Done; return the response. + return response + + async def set_finding_state( + self, + request: securitycenter_service.SetFindingStateRequest = None, + *, + name: str = None, + state: finding.Finding.State = None, + start_time: timestamp.Timestamp = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of a finding. + + Args: + request (:class:`~.securitycenter_service.SetFindingStateRequest`): + The request object. Request message for updating a + finding's state. + name (:class:`str`): + Required. The relative resource name of the finding. + See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (:class:`~.finding.Finding.State`): + Required. The desired State of the + finding. + This corresponds to the ``state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + start_time (:class:`~.timestamp.Timestamp`): + Required. The time at which the + updated state takes effect. + This corresponds to the ``start_time`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.finding.Finding: + Security Command Center finding. + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name, state, start_time]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.SetFindingStateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if state is not None: + request.state = state + if start_time is not None: + request.start_time = start_time + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_finding_state, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def set_iam_policy( + self, + request: iam_policy.SetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Sets the access control policy on the specified + Source. + + Args: + request (:class:`~.iam_policy.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + This corresponds to the ``resource`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([resource]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.SetIamPolicyRequest(**request) + + elif not request: + request = iam_policy.SetIamPolicyRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: iam_policy.TestIamPermissionsRequest = None, + *, + resource: str = None, + permissions: Sequence[str] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy.TestIamPermissionsResponse: + r"""Returns the permissions that a caller has on the + specified source. + + Args: + request (:class:`~.iam_policy.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`Sequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + This corresponds to the ``permissions`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.iam_policy.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([resource, permissions]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.TestIamPermissionsRequest(**request) + + elif not request: + request = iam_policy.TestIamPermissionsRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.resource = resource + + if permissions: + request.permissions.extend(permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_finding( + self, + request: securitycenter_service.UpdateFindingRequest = None, + *, + finding: gcs_finding.Finding = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Args: + request (:class:`~.securitycenter_service.UpdateFindingRequest`): + The request object. Request message for updating or + creating a finding. + finding (:class:`~.gcs_finding.Finding`): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + This corresponds to the ``finding`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_finding.Finding: + Security Command Center finding. + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([finding]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.UpdateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_finding, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("finding.name", request.finding.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_organization_settings( + self, + request: securitycenter_service.UpdateOrganizationSettingsRequest = None, + *, + organization_settings: gcs_organization_settings.OrganizationSettings = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Updates an organization's settings. + + Args: + request (:class:`~.securitycenter_service.UpdateOrganizationSettingsRequest`): + The request object. Request message for updating an + organization's settings. + organization_settings (:class:`~.gcs_organization_settings.OrganizationSettings`): + Required. The organization settings + resource to update. + This corresponds to the ``organization_settings`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_organization_settings.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([organization_settings]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.UpdateOrganizationSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if organization_settings is not None: + request.organization_settings = organization_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_organization_settings, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("organization_settings.name", request.organization_settings.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_source( + self, + request: securitycenter_service.UpdateSourceRequest = None, + *, + source: gcs_source.Source = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Updates a source. + + Args: + request (:class:`~.securitycenter_service.UpdateSourceRequest`): + The request object. Request message for updating a + source. + source (:class:`~.gcs_source.Source`): + Required. The source resource to + update. + This corresponds to the ``source`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([source]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.UpdateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_source, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("source.name", request.source.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_security_marks( + self, + request: securitycenter_service.UpdateSecurityMarksRequest = None, + *, + security_marks: gcs_security_marks.SecurityMarks = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. + + Args: + request (:class:`~.securitycenter_service.UpdateSecurityMarksRequest`): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (:class:`~.gcs_security_marks.SecurityMarks`): + Required. The security marks resource + to update. + This corresponds to the ``security_marks`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_security_marks.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([security_marks]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.UpdateSecurityMarksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if security_marks is not None: + request.security_marks = security_marks + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_security_marks, + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_marks.name", request.security_marks.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-securitycenter", + ).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +__all__ = ("SecurityCenterAsyncClient",) diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/client.py b/google/cloud/securitycenter_v1beta1/services/security_center/client.py new file mode 100644 index 00000000..5e82612a --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/services/security_center/client.py @@ -0,0 +1,1979 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 +import os +import re +from typing import Callable, Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation +from google.api_core import operation_async +from google.cloud.securitycenter_v1beta1.services.security_center import pagers +from google.cloud.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import organization_settings +from google.cloud.securitycenter_v1beta1.types import ( + organization_settings as gcs_organization_settings, +) +from google.cloud.securitycenter_v1beta1.types import security_marks +from google.cloud.securitycenter_v1beta1.types import ( + security_marks as gcs_security_marks, +) +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + +from .transports.base import SecurityCenterTransport +from .transports.grpc import SecurityCenterGrpcTransport +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport + + +class SecurityCenterClientMeta(type): + """Metaclass for the SecurityCenter 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[SecurityCenterTransport]] + _transport_registry["grpc"] = SecurityCenterGrpcTransport + _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[SecurityCenterTransport]: + """Return 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 SecurityCenterClient(metaclass=SecurityCenterClientMeta): + """V1 Beta APIs for Security Center service.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert 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") + + DEFAULT_ENDPOINT = "securitycenter.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @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: + {@api.name}: 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 + + @staticmethod + def finding_path(organization: str, source: str, finding: str,) -> str: + """Return a fully-qualified finding string.""" + return "organizations/{organization}/sources/{source}/findings/{finding}".format( + organization=organization, source=source, finding=finding, + ) + + @staticmethod + def parse_finding_path(path: str) -> Dict[str, str]: + """Parse a finding path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def organization_settings_path(organization: str,) -> str: + """Return a fully-qualified organization_settings string.""" + return "organizations/{organization}/organizationSettings".format( + organization=organization, + ) + + @staticmethod + def parse_organization_settings_path(path: str) -> Dict[str, str]: + """Parse a organization_settings path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/organizationSettings$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def security_marks_path(organization: str, asset: str,) -> str: + """Return a fully-qualified security_marks string.""" + return "organizations/{organization}/assets/{asset}/securityMarks".format( + organization=organization, asset=asset, + ) + + @staticmethod + def parse_security_marks_path(path: str) -> Dict[str, str]: + """Parse a security_marks path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def source_path(organization: str, source: str,) -> str: + """Return a fully-qualified source string.""" + return "organizations/{organization}/sources/{source}".format( + organization=organization, source=source, + ) + + @staticmethod + def parse_source_path(path: str) -> Dict[str, str]: + """Parse a source path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/sources/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, SecurityCenterTransport] = None, + client_options: ClientOptions = None, + ) -> None: + """Instantiate the security center 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. + transport (Union[str, ~.SecurityCenterTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = ClientOptions.from_dict(client_options) + if client_options is None: + client_options = ClientOptions.ClientOptions() + + if client_options.api_endpoint is None: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") + if use_mtls_env == "never": + client_options.api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + has_client_cert_source = ( + client_options.client_cert_source is not None + or mtls.has_default_client_cert_source() + ) + client_options.api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT + if has_client_cert_source + else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SecurityCenterTransport): + # transport is a SecurityCenterTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=client_options.api_endpoint, + scopes=client_options.scopes, + api_mtls_endpoint=client_options.api_endpoint, + client_cert_source=client_options.client_cert_source, + quota_project_id=client_options.quota_project_id, + ) + + def create_source( + self, + request: securitycenter_service.CreateSourceRequest = None, + *, + parent: str = None, + source: gcs_source.Source = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a source. + + Args: + request (:class:`~.securitycenter_service.CreateSourceRequest`): + The request object. Request message for creating a + source. + parent (:class:`str`): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (:class:`~.gcs_source.Source`): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + This corresponds to the ``source`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, source]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.CreateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.create_source, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def create_finding( + self, + request: securitycenter_service.CreateFindingRequest = None, + *, + parent: str = None, + finding_id: str = None, + finding: gcs_finding.Finding = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Args: + request (:class:`~.securitycenter_service.CreateFindingRequest`): + The request object. Request message for creating a + finding. + parent (:class:`str`): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + It must be alphanumeric and less than or + equal to 32 characters and greater than + 0 characters in length. + This corresponds to the ``finding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (:class:`~.gcs_finding.Finding`): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + This corresponds to the ``finding`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_finding.Finding: + Security Command Center finding. + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, finding_id, finding]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.CreateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if finding_id is not None: + request.finding_id = finding_id + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.create_finding, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_iam_policy( + self, + request: iam_policy.GetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Gets the access control policy on the specified + Source. + + Args: + request (:class:`~.iam_policy.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + This corresponds to the ``resource`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([resource]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.GetIamPolicyRequest(**request) + + elif not request: + request = iam_policy.GetIamPolicyRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_organization_settings( + self, + request: securitycenter_service.GetOrganizationSettingsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> organization_settings.OrganizationSettings: + r"""Gets the settings for an organization. + + Args: + request (:class:`~.securitycenter_service.GetOrganizationSettingsRequest`): + The request object. Request message for getting + organization settings. + name (:class:`str`): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + This corresponds to the ``name`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.organization_settings.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.GetOrganizationSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_organization_settings, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_source( + self, + request: securitycenter_service.GetSourceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Gets a source. + + Args: + request (:class:`~.securitycenter_service.GetSourceRequest`): + The request object. Request message for getting a + source. + name (:class:`str`): + Required. Relative resource name of the source. Its + format is + "organizations/[organization_id]/source/[source_id]". + This corresponds to the ``name`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.GetSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_source, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def group_assets( + self, + request: securitycenter_service.GroupAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupAssetsPager: + r"""Filters an organization's assets and groups them by + their specified properties. + + Args: + request (:class:`~.securitycenter_service.GroupAssetsRequest`): + The request object. Request message for grouping by + assets. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.GroupAssetsPager: + Response message for grouping by + assets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + + request = securitycenter_service.GroupAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.group_assets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.GroupAssetsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def group_findings( + self, + request: securitycenter_service.GroupFindingsRequest = None, + *, + parent: str = None, + group_by: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsPager: + r"""Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + Args: + request (:class:`~.securitycenter_service.GroupFindingsRequest`): + The request object. Request message for grouping by + findings. + parent (:class:`str`): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]". + To groupBy across all sources provide a source_id of + ``-``. For example: + organizations/{organization_id}/sources/- + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (:class:`str`): + Required. Expression that defines what assets fields to + use for grouping (including ``state``). The string value + should follow SQL syntax: comma separated list of + fields. For example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + This corresponds to the ``group_by`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.GroupFindingsPager: + Response message for group by + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, group_by]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.GroupFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.group_findings, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.GroupFindingsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def list_assets( + self, + request: securitycenter_service.ListAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsPager: + r"""Lists an organization's assets. + + Args: + request (:class:`~.securitycenter_service.ListAssetsRequest`): + The request object. Request message for listing assets. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListAssetsPager: + Response message for listing assets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + + request = securitycenter_service.ListAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_assets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAssetsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def list_findings( + self, + request: securitycenter_service.ListFindingsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFindingsPager: + r"""Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + Args: + request (:class:`~.securitycenter_service.ListFindingsRequest`): + The request object. Request message for listing + findings. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListFindingsPager: + Response message for listing + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + + request = securitycenter_service.ListFindingsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_findings, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListFindingsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def list_sources( + self, + request: securitycenter_service.ListSourcesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSourcesPager: + r"""Lists all sources belonging to an organization. + + Args: + request (:class:`~.securitycenter_service.ListSourcesRequest`): + The request object. Request message for listing sources. + parent (:class:`str`): + Required. Resource name of the parent of sources to + list. Its format should be + "organizations/[organization_id]". + This corresponds to the ``parent`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListSourcesPager: + Response message for listing sources. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.ListSourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_sources, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListSourcesPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def run_asset_discovery( + self, + request: securitycenter_service.RunAssetDiscoveryRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Args: + request (:class:`~.securitycenter_service.RunAssetDiscoveryRequest`): + The request object. Request message for running asset + discovery for an organization. + parent (:class:`str`): + Required. Name of the organization to run asset + discovery for. Its format is + "organizations/[organization_id]". + This corresponds to the ``parent`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.empty.Empty``: A generic empty message that + you can re-use to avoid defining duplicated empty + messages in your APIs. A typical example is to use it as + the request or the response type of an API method. For + instance: + + :: + + service Foo { + rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); + } + + The JSON representation for ``Empty`` is empty JSON + object ``{}``. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.RunAssetDiscoveryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.run_asset_discovery, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + empty.Empty, + metadata_type=empty.Empty, + ) + + # Done; return the response. + return response + + def set_finding_state( + self, + request: securitycenter_service.SetFindingStateRequest = None, + *, + name: str = None, + state: finding.Finding.State = None, + start_time: timestamp.Timestamp = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of a finding. + + Args: + request (:class:`~.securitycenter_service.SetFindingStateRequest`): + The request object. Request message for updating a + finding's state. + name (:class:`str`): + Required. The relative resource name of the finding. + See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (:class:`~.finding.Finding.State`): + Required. The desired State of the + finding. + This corresponds to the ``state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + start_time (:class:`~.timestamp.Timestamp`): + Required. The time at which the + updated state takes effect. + This corresponds to the ``start_time`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.finding.Finding: + Security Command Center finding. + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name, state, start_time]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.SetFindingStateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if state is not None: + request.state = state + if start_time is not None: + request.start_time = start_time + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_finding_state, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def set_iam_policy( + self, + request: iam_policy.SetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Sets the access control policy on the specified + Source. + + Args: + request (:class:`~.iam_policy.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + This corresponds to the ``resource`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([resource]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.SetIamPolicyRequest(**request) + + elif not request: + request = iam_policy.SetIamPolicyRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: iam_policy.TestIamPermissionsRequest = None, + *, + resource: str = None, + permissions: Sequence[str] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy.TestIamPermissionsResponse: + r"""Returns the permissions that a caller has on the + specified source. + + Args: + request (:class:`~.iam_policy.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`Sequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + This corresponds to the ``permissions`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.iam_policy.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([resource, permissions]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.TestIamPermissionsRequest(**request) + + elif not request: + request = iam_policy.TestIamPermissionsRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.resource = resource + + if permissions: + request.permissions.extend(permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_finding( + self, + request: securitycenter_service.UpdateFindingRequest = None, + *, + finding: gcs_finding.Finding = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Args: + request (:class:`~.securitycenter_service.UpdateFindingRequest`): + The request object. Request message for updating or + creating a finding. + finding (:class:`~.gcs_finding.Finding`): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + This corresponds to the ``finding`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_finding.Finding: + Security Command Center finding. + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([finding]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.UpdateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.update_finding, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("finding.name", request.finding.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_organization_settings( + self, + request: securitycenter_service.UpdateOrganizationSettingsRequest = None, + *, + organization_settings: gcs_organization_settings.OrganizationSettings = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Updates an organization's settings. + + Args: + request (:class:`~.securitycenter_service.UpdateOrganizationSettingsRequest`): + The request object. Request message for updating an + organization's settings. + organization_settings (:class:`~.gcs_organization_settings.OrganizationSettings`): + Required. The organization settings + resource to update. + This corresponds to the ``organization_settings`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_organization_settings.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([organization_settings]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.UpdateOrganizationSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if organization_settings is not None: + request.organization_settings = organization_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.update_organization_settings, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("organization_settings.name", request.organization_settings.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_source( + self, + request: securitycenter_service.UpdateSourceRequest = None, + *, + source: gcs_source.Source = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Updates a source. + + Args: + request (:class:`~.securitycenter_service.UpdateSourceRequest`): + The request object. Request message for updating a + source. + source (:class:`~.gcs_source.Source`): + Required. The source resource to + update. + This corresponds to the ``source`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([source]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.UpdateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.update_source, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("source.name", request.source.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_security_marks( + self, + request: securitycenter_service.UpdateSecurityMarksRequest = None, + *, + security_marks: gcs_security_marks.SecurityMarks = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. + + Args: + request (:class:`~.securitycenter_service.UpdateSecurityMarksRequest`): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (:class:`~.gcs_security_marks.SecurityMarks`): + Required. The security marks resource + to update. + This corresponds to the ``security_marks`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_security_marks.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([security_marks]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.UpdateSecurityMarksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if security_marks is not None: + request.security_marks = security_marks + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.update_security_marks, + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_marks.name", request.security_marks.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-securitycenter", + ).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +__all__ = ("SecurityCenterClient",) diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py b/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py new file mode 100644 index 00000000..64ef79bd --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py @@ -0,0 +1,668 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple + +from google.cloud.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source + + +class GroupAssetsPager: + """A pager for iterating through ``group_assets`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.GroupAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GroupAssets`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.GroupAssetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., securitycenter_service.GroupAssetsResponse], + request: securitycenter_service.GroupAssetsRequest, + response: securitycenter_service.GroupAssetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.GroupAssetsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.GroupAssetsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.GroupAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.GroupAssetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[securitycenter_service.GroupResult]: + for page in self.pages: + yield from page.group_by_results + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class GroupAssetsAsyncPager: + """A pager for iterating through ``group_assets`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.GroupAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GroupAssets`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.GroupAssetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[securitycenter_service.GroupAssetsResponse]], + request: securitycenter_service.GroupAssetsRequest, + response: securitycenter_service.GroupAssetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.GroupAssetsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.GroupAssetsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.GroupAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.GroupAssetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[securitycenter_service.GroupResult]: + async def async_generator(): + async for page in self.pages: + for response in page.group_by_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class GroupFindingsPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.GroupFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.GroupFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., securitycenter_service.GroupFindingsResponse], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.GroupFindingsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.GroupFindingsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.GroupFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.GroupFindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[securitycenter_service.GroupResult]: + for page in self.pages: + yield from page.group_by_results + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class GroupFindingsAsyncPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.GroupFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.GroupFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[securitycenter_service.GroupFindingsResponse]], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.GroupFindingsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.GroupFindingsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.GroupFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterable[securitycenter_service.GroupFindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[securitycenter_service.GroupResult]: + async def async_generator(): + async for page in self.pages: + for response in page.group_by_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAssetsPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.ListAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``list_assets_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``list_assets_results`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.ListAssetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., securitycenter_service.ListAssetsResponse], + request: securitycenter_service.ListAssetsRequest, + response: securitycenter_service.ListAssetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListAssetsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.ListAssetsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.ListAssetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__( + self, + ) -> Iterable[securitycenter_service.ListAssetsResponse.ListAssetsResult]: + for page in self.pages: + yield from page.list_assets_results + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAssetsAsyncPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.ListAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``list_assets_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``list_assets_results`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.ListAssetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[securitycenter_service.ListAssetsResponse]], + request: securitycenter_service.ListAssetsRequest, + response: securitycenter_service.ListAssetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListAssetsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.ListAssetsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.ListAssetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__( + self, + ) -> AsyncIterable[securitycenter_service.ListAssetsResponse.ListAssetsResult]: + async def async_generator(): + async for page in self.pages: + for response in page.list_assets_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListFindingsPager: + """A pager for iterating through ``list_findings`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.ListFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``findings`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``findings`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.ListFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., securitycenter_service.ListFindingsResponse], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.ListFindingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListFindingsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.ListFindingsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.ListFindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[finding.Finding]: + for page in self.pages: + yield from page.findings + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListFindingsAsyncPager: + """A pager for iterating through ``list_findings`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.ListFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``findings`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``findings`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.ListFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[securitycenter_service.ListFindingsResponse]], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.ListFindingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListFindingsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.ListFindingsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.ListFindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[finding.Finding]: + async def async_generator(): + async for page in self.pages: + for response in page.findings: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSourcesPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.ListSourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.ListSourcesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., securitycenter_service.ListSourcesResponse], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListSourcesRequest`): + The initial request object. + response (:class:`~.securitycenter_service.ListSourcesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListSourcesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.ListSourcesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[source.Source]: + for page in self.pages: + yield from page.sources + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSourcesAsyncPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.ListSourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.ListSourcesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[securitycenter_service.ListSourcesResponse]], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListSourcesRequest`): + The initial request object. + response (:class:`~.securitycenter_service.ListSourcesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListSourcesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.ListSourcesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[source.Source]: + async def async_generator(): + async for page in self.pages: + for response in page.sources: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py b/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py new file mode 100644 index 00000000..20423f2a --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 typing import Dict, Type + +from .base import SecurityCenterTransport +from .grpc import SecurityCenterGrpcTransport +from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] +_transport_registry["grpc"] = SecurityCenterGrpcTransport +_transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport + + +__all__ = ( + "SecurityCenterTransport", + "SecurityCenterGrpcTransport", + "SecurityCenterGrpcAsyncIOTransport", +) diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py b/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py new file mode 100644 index 00000000..0729c7d6 --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py @@ -0,0 +1,294 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 +import typing + +from google import auth +from google.api_core import exceptions # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import organization_settings +from google.cloud.securitycenter_v1beta1.types import ( + organization_settings as gcs_organization_settings, +) +from google.cloud.securitycenter_v1beta1.types import ( + security_marks as gcs_security_marks, +) +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.longrunning import operations_pb2 as operations # type: ignore + + +class SecurityCenterTransport(abc.ABC): + """Abstract transport class for SecurityCenter.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + def __init__( + self, + *, + host: str = "securitycenter.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + 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]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_source( + self, + ) -> typing.Callable[ + [securitycenter_service.CreateSourceRequest], + typing.Union[gcs_source.Source, typing.Awaitable[gcs_source.Source]], + ]: + raise NotImplementedError() + + @property + def create_finding( + self, + ) -> typing.Callable[ + [securitycenter_service.CreateFindingRequest], + typing.Union[gcs_finding.Finding, typing.Awaitable[gcs_finding.Finding]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> typing.Callable[ + [iam_policy.GetIamPolicyRequest], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ]: + raise NotImplementedError() + + @property + def get_organization_settings( + self, + ) -> typing.Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + typing.Union[ + organization_settings.OrganizationSettings, + typing.Awaitable[organization_settings.OrganizationSettings], + ], + ]: + raise NotImplementedError() + + @property + def get_source( + self, + ) -> typing.Callable[ + [securitycenter_service.GetSourceRequest], + typing.Union[source.Source, typing.Awaitable[source.Source]], + ]: + raise NotImplementedError() + + @property + def group_assets( + self, + ) -> typing.Callable[ + [securitycenter_service.GroupAssetsRequest], + typing.Union[ + securitycenter_service.GroupAssetsResponse, + typing.Awaitable[securitycenter_service.GroupAssetsResponse], + ], + ]: + raise NotImplementedError() + + @property + def group_findings( + self, + ) -> typing.Callable[ + [securitycenter_service.GroupFindingsRequest], + typing.Union[ + securitycenter_service.GroupFindingsResponse, + typing.Awaitable[securitycenter_service.GroupFindingsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_assets( + self, + ) -> typing.Callable[ + [securitycenter_service.ListAssetsRequest], + typing.Union[ + securitycenter_service.ListAssetsResponse, + typing.Awaitable[securitycenter_service.ListAssetsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_findings( + self, + ) -> typing.Callable[ + [securitycenter_service.ListFindingsRequest], + typing.Union[ + securitycenter_service.ListFindingsResponse, + typing.Awaitable[securitycenter_service.ListFindingsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_sources( + self, + ) -> typing.Callable[ + [securitycenter_service.ListSourcesRequest], + typing.Union[ + securitycenter_service.ListSourcesResponse, + typing.Awaitable[securitycenter_service.ListSourcesResponse], + ], + ]: + raise NotImplementedError() + + @property + def run_asset_discovery( + self, + ) -> typing.Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + @property + def set_finding_state( + self, + ) -> typing.Callable[ + [securitycenter_service.SetFindingStateRequest], + typing.Union[finding.Finding, typing.Awaitable[finding.Finding]], + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> typing.Callable[ + [iam_policy.SetIamPolicyRequest], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> typing.Callable[ + [iam_policy.TestIamPermissionsRequest], + typing.Union[ + iam_policy.TestIamPermissionsResponse, + typing.Awaitable[iam_policy.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def update_finding( + self, + ) -> typing.Callable[ + [securitycenter_service.UpdateFindingRequest], + typing.Union[gcs_finding.Finding, typing.Awaitable[gcs_finding.Finding]], + ]: + raise NotImplementedError() + + @property + def update_organization_settings( + self, + ) -> typing.Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + typing.Union[ + gcs_organization_settings.OrganizationSettings, + typing.Awaitable[gcs_organization_settings.OrganizationSettings], + ], + ]: + raise NotImplementedError() + + @property + def update_source( + self, + ) -> typing.Callable[ + [securitycenter_service.UpdateSourceRequest], + typing.Union[gcs_source.Source, typing.Awaitable[gcs_source.Source]], + ]: + raise NotImplementedError() + + @property + def update_security_marks( + self, + ) -> typing.Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + typing.Union[ + gcs_security_marks.SecurityMarks, + typing.Awaitable[gcs_security_marks.SecurityMarks], + ], + ]: + raise NotImplementedError() + + +__all__ = ("SecurityCenterTransport",) diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py b/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py new file mode 100644 index 00000000..45296ba3 --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py @@ -0,0 +1,754 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + + +import grpc # type: ignore + +from google.cloud.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import organization_settings +from google.cloud.securitycenter_v1beta1.types import ( + organization_settings as gcs_organization_settings, +) +from google.cloud.securitycenter_v1beta1.types import ( + security_marks as gcs_security_marks, +) +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.longrunning import operations_pb2 as operations # type: ignore + +from .base import SecurityCenterTransport + + +class SecurityCenterGrpcTransport(SecurityCenterTransport): + """gRPC backend transport for SecurityCenter. + + V1 Beta APIs for Security Center service. + + 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 = "securitycenter.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + 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 ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): 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 applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + 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. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + @classmethod + def create_channel( + cls, + host: str = "securitycenter.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[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]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional 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. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def create_source( + self, + ) -> Callable[[securitycenter_service.CreateSourceRequest], gcs_source.Source]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + ~.Source]: + 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_source" not in self._stubs: + self._stubs["create_source"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateSource", + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs["create_source"] + + @property + def create_finding( + self, + ) -> Callable[[securitycenter_service.CreateFindingRequest], gcs_finding.Finding]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + ~.Finding]: + 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_finding" not in self._stubs: + self._stubs["create_finding"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateFinding", + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs["create_finding"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy.GetIamPolicyRequest], policy.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the access control policy on the specified + Source. + + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + 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 "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/GetIamPolicy", + request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def get_organization_settings( + self, + ) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + organization_settings.OrganizationSettings, + ]: + r"""Return a callable for the get organization settings method over gRPC. + + Gets the settings for an organization. + + Returns: + Callable[[~.GetOrganizationSettingsRequest], + ~.OrganizationSettings]: + 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 "get_organization_settings" not in self._stubs: + self._stubs["get_organization_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/GetOrganizationSettings", + request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, + response_deserializer=organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs["get_organization_settings"] + + @property + def get_source( + self, + ) -> Callable[[securitycenter_service.GetSourceRequest], source.Source]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + ~.Source]: + 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 "get_source" not in self._stubs: + self._stubs["get_source"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/GetSource", + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs["get_source"] + + @property + def group_assets( + self, + ) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + securitycenter_service.GroupAssetsResponse, + ]: + r"""Return a callable for the group assets method over gRPC. + + Filters an organization's assets and groups them by + their specified properties. + + Returns: + Callable[[~.GroupAssetsRequest], + ~.GroupAssetsResponse]: + 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 "group_assets" not in self._stubs: + self._stubs["group_assets"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupAssets", + request_serializer=securitycenter_service.GroupAssetsRequest.serialize, + response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, + ) + return self._stubs["group_assets"] + + @property + def group_findings( + self, + ) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + securitycenter_service.GroupFindingsResponse, + ]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + Returns: + Callable[[~.GroupFindingsRequest], + ~.GroupFindingsResponse]: + 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 "group_findings" not in self._stubs: + self._stubs["group_findings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupFindings", + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs["group_findings"] + + @property + def list_assets( + self, + ) -> Callable[ + [securitycenter_service.ListAssetsRequest], + securitycenter_service.ListAssetsResponse, + ]: + r"""Return a callable for the list assets method over gRPC. + + Lists an organization's assets. + + Returns: + Callable[[~.ListAssetsRequest], + ~.ListAssetsResponse]: + 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 "list_assets" not in self._stubs: + self._stubs["list_assets"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/ListAssets", + request_serializer=securitycenter_service.ListAssetsRequest.serialize, + response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, + ) + return self._stubs["list_assets"] + + @property + def list_findings( + self, + ) -> Callable[ + [securitycenter_service.ListFindingsRequest], + securitycenter_service.ListFindingsResponse, + ]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + Returns: + Callable[[~.ListFindingsRequest], + ~.ListFindingsResponse]: + 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 "list_findings" not in self._stubs: + self._stubs["list_findings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/ListFindings", + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs["list_findings"] + + @property + def list_sources( + self, + ) -> Callable[ + [securitycenter_service.ListSourcesRequest], + securitycenter_service.ListSourcesResponse, + ]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + ~.ListSourcesResponse]: + 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 "list_sources" not in self._stubs: + self._stubs["list_sources"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/ListSources", + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs["list_sources"] + + @property + def run_asset_discovery( + self, + ) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], operations.Operation + ]: + r"""Return a callable for the run asset discovery method over gRPC. + + Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Returns: + Callable[[~.RunAssetDiscoveryRequest], + ~.Operation]: + 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 "run_asset_discovery" not in self._stubs: + self._stubs["run_asset_discovery"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/RunAssetDiscovery", + request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["run_asset_discovery"] + + @property + def set_finding_state( + self, + ) -> Callable[[securitycenter_service.SetFindingStateRequest], finding.Finding]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. + + Returns: + Callable[[~.SetFindingStateRequest], + ~.Finding]: + 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 "set_finding_state" not in self._stubs: + self._stubs["set_finding_state"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/SetFindingState", + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs["set_finding_state"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy.SetIamPolicyRequest], policy.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the access control policy on the specified + Source. + + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + 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 "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/SetIamPolicy", + request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy.TestIamPermissionsRequest], iam_policy.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns the permissions that a caller has on the + specified source. + + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + 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 "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/TestIamPermissions", + request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def update_finding( + self, + ) -> Callable[[securitycenter_service.UpdateFindingRequest], gcs_finding.Finding]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + ~.Finding]: + 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_finding" not in self._stubs: + self._stubs["update_finding"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateFinding", + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs["update_finding"] + + @property + def update_organization_settings( + self, + ) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + gcs_organization_settings.OrganizationSettings, + ]: + r"""Return a callable for the update organization settings method over gRPC. + + Updates an organization's settings. + + Returns: + Callable[[~.UpdateOrganizationSettingsRequest], + ~.OrganizationSettings]: + 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_organization_settings" not in self._stubs: + self._stubs["update_organization_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateOrganizationSettings", + request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, + response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs["update_organization_settings"] + + @property + def update_source( + self, + ) -> Callable[[securitycenter_service.UpdateSourceRequest], gcs_source.Source]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + ~.Source]: + 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_source" not in self._stubs: + self._stubs["update_source"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSource", + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs["update_source"] + + @property + def update_security_marks( + self, + ) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + gcs_security_marks.SecurityMarks, + ]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + ~.SecurityMarks]: + 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_security_marks" not in self._stubs: + self._stubs["update_security_marks"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSecurityMarks", + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs["update_security_marks"] + + +__all__ = ("SecurityCenterGrpcTransport",) diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py b/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py new file mode 100644 index 00000000..c3d7b5db --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py @@ -0,0 +1,759 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.securitycenter_v1beta1.types import finding +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import organization_settings +from google.cloud.securitycenter_v1beta1.types import ( + organization_settings as gcs_organization_settings, +) +from google.cloud.securitycenter_v1beta1.types import ( + security_marks as gcs_security_marks, +) +from google.cloud.securitycenter_v1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1beta1.types import source +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.longrunning import operations_pb2 as operations # type: ignore + +from .base import SecurityCenterTransport +from .grpc import SecurityCenterGrpcTransport + + +class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): + """gRPC AsyncIO backend transport for SecurityCenter. + + V1 Beta APIs for Security Center service. + + 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 = "securitycenter.googleapis.com", + credentials: 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: + address (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]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional 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. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "securitycenter.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + 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 ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional 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[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): 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 applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + 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. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} + + @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. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def create_source( + self, + ) -> Callable[ + [securitycenter_service.CreateSourceRequest], Awaitable[gcs_source.Source] + ]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + Awaitable[~.Source]]: + 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_source" not in self._stubs: + self._stubs["create_source"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateSource", + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs["create_source"] + + @property + def create_finding( + self, + ) -> Callable[ + [securitycenter_service.CreateFindingRequest], Awaitable[gcs_finding.Finding] + ]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + Awaitable[~.Finding]]: + 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_finding" not in self._stubs: + self._stubs["create_finding"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateFinding", + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs["create_finding"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy.GetIamPolicyRequest], Awaitable[policy.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the access control policy on the specified + Source. + + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.Policy]]: + 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 "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/GetIamPolicy", + request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def get_organization_settings( + self, + ) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + Awaitable[organization_settings.OrganizationSettings], + ]: + r"""Return a callable for the get organization settings method over gRPC. + + Gets the settings for an organization. + + Returns: + Callable[[~.GetOrganizationSettingsRequest], + Awaitable[~.OrganizationSettings]]: + 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 "get_organization_settings" not in self._stubs: + self._stubs["get_organization_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/GetOrganizationSettings", + request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, + response_deserializer=organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs["get_organization_settings"] + + @property + def get_source( + self, + ) -> Callable[[securitycenter_service.GetSourceRequest], Awaitable[source.Source]]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + Awaitable[~.Source]]: + 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 "get_source" not in self._stubs: + self._stubs["get_source"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/GetSource", + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs["get_source"] + + @property + def group_assets( + self, + ) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + Awaitable[securitycenter_service.GroupAssetsResponse], + ]: + r"""Return a callable for the group assets method over gRPC. + + Filters an organization's assets and groups them by + their specified properties. + + Returns: + Callable[[~.GroupAssetsRequest], + Awaitable[~.GroupAssetsResponse]]: + 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 "group_assets" not in self._stubs: + self._stubs["group_assets"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupAssets", + request_serializer=securitycenter_service.GroupAssetsRequest.serialize, + response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, + ) + return self._stubs["group_assets"] + + @property + def group_findings( + self, + ) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + Awaitable[securitycenter_service.GroupFindingsResponse], + ]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + Returns: + Callable[[~.GroupFindingsRequest], + Awaitable[~.GroupFindingsResponse]]: + 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 "group_findings" not in self._stubs: + self._stubs["group_findings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupFindings", + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs["group_findings"] + + @property + def list_assets( + self, + ) -> Callable[ + [securitycenter_service.ListAssetsRequest], + Awaitable[securitycenter_service.ListAssetsResponse], + ]: + r"""Return a callable for the list assets method over gRPC. + + Lists an organization's assets. + + Returns: + Callable[[~.ListAssetsRequest], + Awaitable[~.ListAssetsResponse]]: + 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 "list_assets" not in self._stubs: + self._stubs["list_assets"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/ListAssets", + request_serializer=securitycenter_service.ListAssetsRequest.serialize, + response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, + ) + return self._stubs["list_assets"] + + @property + def list_findings( + self, + ) -> Callable[ + [securitycenter_service.ListFindingsRequest], + Awaitable[securitycenter_service.ListFindingsResponse], + ]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1beta1/organizations/{organization_id}/sources/-/findings + + Returns: + Callable[[~.ListFindingsRequest], + Awaitable[~.ListFindingsResponse]]: + 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 "list_findings" not in self._stubs: + self._stubs["list_findings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/ListFindings", + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs["list_findings"] + + @property + def list_sources( + self, + ) -> Callable[ + [securitycenter_service.ListSourcesRequest], + Awaitable[securitycenter_service.ListSourcesResponse], + ]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + Awaitable[~.ListSourcesResponse]]: + 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 "list_sources" not in self._stubs: + self._stubs["list_sources"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/ListSources", + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs["list_sources"] + + @property + def run_asset_discovery( + self, + ) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + Awaitable[operations.Operation], + ]: + r"""Return a callable for the run asset discovery method over gRPC. + + Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Returns: + Callable[[~.RunAssetDiscoveryRequest], + Awaitable[~.Operation]]: + 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 "run_asset_discovery" not in self._stubs: + self._stubs["run_asset_discovery"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/RunAssetDiscovery", + request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["run_asset_discovery"] + + @property + def set_finding_state( + self, + ) -> Callable[ + [securitycenter_service.SetFindingStateRequest], Awaitable[finding.Finding] + ]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. + + Returns: + Callable[[~.SetFindingStateRequest], + Awaitable[~.Finding]]: + 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 "set_finding_state" not in self._stubs: + self._stubs["set_finding_state"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/SetFindingState", + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs["set_finding_state"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy.SetIamPolicyRequest], Awaitable[policy.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the access control policy on the specified + Source. + + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.Policy]]: + 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 "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/SetIamPolicy", + request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy.TestIamPermissionsRequest], + Awaitable[iam_policy.TestIamPermissionsResponse], + ]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns the permissions that a caller has on the + specified source. + + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.TestIamPermissionsResponse]]: + 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 "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/TestIamPermissions", + request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def update_finding( + self, + ) -> Callable[ + [securitycenter_service.UpdateFindingRequest], Awaitable[gcs_finding.Finding] + ]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + Awaitable[~.Finding]]: + 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_finding" not in self._stubs: + self._stubs["update_finding"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateFinding", + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs["update_finding"] + + @property + def update_organization_settings( + self, + ) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + Awaitable[gcs_organization_settings.OrganizationSettings], + ]: + r"""Return a callable for the update organization settings method over gRPC. + + Updates an organization's settings. + + Returns: + Callable[[~.UpdateOrganizationSettingsRequest], + Awaitable[~.OrganizationSettings]]: + 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_organization_settings" not in self._stubs: + self._stubs["update_organization_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateOrganizationSettings", + request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, + response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs["update_organization_settings"] + + @property + def update_source( + self, + ) -> Callable[ + [securitycenter_service.UpdateSourceRequest], Awaitable[gcs_source.Source] + ]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + Awaitable[~.Source]]: + 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_source" not in self._stubs: + self._stubs["update_source"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSource", + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs["update_source"] + + @property + def update_security_marks( + self, + ) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + Awaitable[gcs_security_marks.SecurityMarks], + ]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + Awaitable[~.SecurityMarks]]: + 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_security_marks" not in self._stubs: + self._stubs["update_security_marks"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSecurityMarks", + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs["update_security_marks"] + + +__all__ = ("SecurityCenterGrpcAsyncIOTransport",) diff --git a/google/cloud/securitycenter_v1beta1/types/__init__.py b/google/cloud/securitycenter_v1beta1/types/__init__.py new file mode 100644 index 00000000..50ef54be --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/types/__init__.py @@ -0,0 +1,77 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 .security_marks import SecurityMarks +from .asset import Asset +from .finding import Finding +from .organization_settings import OrganizationSettings +from .run_asset_discovery_response import RunAssetDiscoveryResponse +from .source import Source +from .securitycenter_service import ( + CreateFindingRequest, + CreateSourceRequest, + GetOrganizationSettingsRequest, + GetSourceRequest, + GroupAssetsRequest, + GroupAssetsResponse, + GroupFindingsRequest, + GroupFindingsResponse, + GroupResult, + ListSourcesRequest, + ListSourcesResponse, + ListAssetsRequest, + ListAssetsResponse, + ListFindingsRequest, + ListFindingsResponse, + SetFindingStateRequest, + RunAssetDiscoveryRequest, + UpdateFindingRequest, + UpdateOrganizationSettingsRequest, + UpdateSourceRequest, + UpdateSecurityMarksRequest, +) + + +__all__ = ( + "SecurityMarks", + "Asset", + "Finding", + "OrganizationSettings", + "RunAssetDiscoveryResponse", + "Source", + "CreateFindingRequest", + "CreateSourceRequest", + "GetOrganizationSettingsRequest", + "GetSourceRequest", + "GroupAssetsRequest", + "GroupAssetsResponse", + "GroupFindingsRequest", + "GroupFindingsResponse", + "GroupResult", + "ListSourcesRequest", + "ListSourcesResponse", + "ListAssetsRequest", + "ListAssetsResponse", + "ListFindingsRequest", + "ListFindingsResponse", + "SetFindingStateRequest", + "RunAssetDiscoveryRequest", + "UpdateFindingRequest", + "UpdateOrganizationSettingsRequest", + "UpdateSourceRequest", + "UpdateSecurityMarksRequest", +) diff --git a/google/cloud/securitycenter_v1beta1/types/asset.py b/google/cloud/securitycenter_v1beta1/types/asset.py new file mode 100644 index 00000000..80b4082d --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/types/asset.py @@ -0,0 +1,129 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +from google.cloud.securitycenter_v1beta1.types import ( + security_marks as gcs_security_marks, +) +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1beta1", manifest={"Asset",}, +) + + +class Asset(proto.Message): + r"""Security Command Center representation of a Google Cloud + resource. + + The Asset is a Security Command Center resource that captures + information about a single Google Cloud resource. All + modifications to an Asset are only within the context of + Security Command Center and don't affect the referenced Google + Cloud resource. + + Attributes: + name (str): + The relative resource name of this asset. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/assets/{asset_id}". + security_center_properties (~.asset.Asset.SecurityCenterProperties): + Security Command Center managed properties. + These properties are managed by Security Command + Center and cannot be modified by the user. + resource_properties (Sequence[~.asset.Asset.ResourcePropertiesEntry]): + Resource managed properties. These properties + are managed and defined by the Google Cloud + resource and cannot be modified by the user. + security_marks (~.gcs_security_marks.SecurityMarks): + User specified security marks. These marks + are entirely managed by the user and come from + the SecurityMarks resource that belongs to the + asset. + create_time (~.timestamp.Timestamp): + The time at which the asset was created in + Security Command Center. + update_time (~.timestamp.Timestamp): + The time at which the asset was last updated, + added, or deleted in Security Command Center. + """ + + class SecurityCenterProperties(proto.Message): + r"""Security Command Center managed properties. These properties + are managed by Security Command Center and cannot be modified by + the user. + + Attributes: + resource_name (str): + Immutable. The full resource name of the Google Cloud + resource this asset represents. This field is immutable + after create time. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_type (str): + The type of the Google Cloud resource. + Examples include: APPLICATION, PROJECT, and + ORGANIZATION. This is a case insensitive field + defined by Security Command Center and/or the + producer of the resource and is immutable after + create time. + resource_parent (str): + The full resource name of the immediate parent of the + resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_project (str): + The full resource name of the project the resource belongs + to. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_owners (Sequence[str]): + Owners of the Google Cloud resource. + """ + + resource_name = proto.Field(proto.STRING, number=1) + + resource_type = proto.Field(proto.STRING, number=2) + + resource_parent = proto.Field(proto.STRING, number=3) + + resource_project = proto.Field(proto.STRING, number=4) + + resource_owners = proto.RepeatedField(proto.STRING, number=5) + + name = proto.Field(proto.STRING, number=1) + + security_center_properties = proto.Field( + proto.MESSAGE, number=2, message=SecurityCenterProperties, + ) + + resource_properties = proto.MapField( + proto.STRING, proto.MESSAGE, number=7, message=struct.Value, + ) + + security_marks = proto.Field( + proto.MESSAGE, number=8, message=gcs_security_marks.SecurityMarks, + ) + + create_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) + + update_time = proto.Field(proto.MESSAGE, number=10, message=timestamp.Timestamp,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1beta1/types/finding.py b/google/cloud/securitycenter_v1beta1/types/finding.py new file mode 100644 index 00000000..847a4f8e --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/types/finding.py @@ -0,0 +1,125 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +from google.cloud.securitycenter_v1beta1.types import ( + security_marks as gcs_security_marks, +) +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1beta1", manifest={"Finding",}, +) + + +class Finding(proto.Message): + r"""Security Command Center finding. + A finding is a record of assessment data (security, risk, health + or privacy) ingested into Security Command Center for + presentation, notification, analysis, policy testing, and + enforcement. For example, an XSS vulnerability in an App Engine + application is a finding. + + Attributes: + name (str): + The relative resource name of this finding. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}". + parent (str): + Immutable. The relative resource name of the source the + finding belongs to. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + This field is immutable after creation time. For example: + "organizations/{organization_id}/sources/{source_id}". + resource_name (str): + For findings on Google Cloud resources, the full resource + name of the Google Cloud resource this finding is for. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + When the finding is for a non-Google Cloud resource, the + resourceName can be a customer or partner defined string. + This field is immutable after creation time. + state (~.finding.Finding.State): + The state of the finding. + category (str): + The additional taxonomy group within findings from a given + source. This field is immutable after creation time. + Example: "XSS_FLASH_INJECTION". + external_uri (str): + The URI that, if available, points to a web + page outside of Security Command Center where + additional information about the finding can be + found. This field is guaranteed to be either + empty or a well formed URL. + source_properties (Sequence[~.finding.Finding.SourcePropertiesEntry]): + Source specific properties. These properties are managed by + the source that writes the finding. The key names in the + source_properties map must be between 1 and 255 characters, + and must start with a letter and contain alphanumeric + characters or underscores only. + security_marks (~.gcs_security_marks.SecurityMarks): + Output only. User specified security marks. + These marks are entirely managed by the user and + come from the SecurityMarks resource that + belongs to the finding. + event_time (~.timestamp.Timestamp): + The time at which the event took place. For + example, if the finding represents an open + firewall it would capture the time the detector + believes the firewall became open. The accuracy + is determined by the detector. + create_time (~.timestamp.Timestamp): + The time at which the finding was created in + Security Command Center. + """ + + class State(proto.Enum): + r"""The state of the finding.""" + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + INACTIVE = 2 + + name = proto.Field(proto.STRING, number=1) + + parent = proto.Field(proto.STRING, number=2) + + resource_name = proto.Field(proto.STRING, number=3) + + state = proto.Field(proto.ENUM, number=4, enum=State,) + + category = proto.Field(proto.STRING, number=5) + + external_uri = proto.Field(proto.STRING, number=6) + + source_properties = proto.MapField( + proto.STRING, proto.MESSAGE, number=7, message=struct.Value, + ) + + security_marks = proto.Field( + proto.MESSAGE, number=8, message=gcs_security_marks.SecurityMarks, + ) + + event_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) + + create_time = proto.Field(proto.MESSAGE, number=10, message=timestamp.Timestamp,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1beta1/types/organization_settings.py b/google/cloud/securitycenter_v1beta1/types/organization_settings.py new file mode 100644 index 00000000..3b3ae0b1 --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/types/organization_settings.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1beta1", manifest={"OrganizationSettings",}, +) + + +class OrganizationSettings(proto.Message): + r"""User specified settings that are attached to the Security + Command Center organization. + + Attributes: + name (str): + The relative resource name of the settings. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/organizationSettings". + enable_asset_discovery (bool): + A flag that indicates if Asset Discovery should be enabled. + If the flag is set to ``true``, then discovery of assets + will occur. If it is set to \`false, all historical assets + will remain, but discovery of future assets will not occur. + asset_discovery_config (~.organization_settings.OrganizationSettings.AssetDiscoveryConfig): + The configuration used for Asset Discovery + runs. + """ + + class AssetDiscoveryConfig(proto.Message): + r"""The configuration used for Asset Discovery runs. + + Attributes: + project_ids (Sequence[str]): + The project ids to use for filtering asset + discovery. + inclusion_mode (~.organization_settings.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): + The mode to use for filtering asset + discovery. + """ + + class InclusionMode(proto.Enum): + r"""The mode of inclusion when running Asset Discovery. Asset discovery + can be limited by explicitly identifying projects to be included or + excluded. If INCLUDE_ONLY is set, then only those projects within + the organization and their children are discovered during asset + discovery. If EXCLUDE is set, then projects that don't match those + projects are discovered during asset discovery. If neither are set, + then all projects within the organization are discovered during + asset discovery. + """ + INCLUSION_MODE_UNSPECIFIED = 0 + INCLUDE_ONLY = 1 + EXCLUDE = 2 + + project_ids = proto.RepeatedField(proto.STRING, number=1) + + inclusion_mode = proto.Field( + proto.ENUM, + number=2, + enum="OrganizationSettings.AssetDiscoveryConfig.InclusionMode", + ) + + name = proto.Field(proto.STRING, number=1) + + enable_asset_discovery = proto.Field(proto.BOOL, number=2) + + asset_discovery_config = proto.Field( + proto.MESSAGE, number=3, message=AssetDiscoveryConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py b/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py new file mode 100644 index 00000000..0b9e9d95 --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +from google.protobuf import duration_pb2 as gp_duration # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1beta1", + manifest={"RunAssetDiscoveryResponse",}, +) + + +class RunAssetDiscoveryResponse(proto.Message): + r"""Response of asset discovery run + + Attributes: + state (~.run_asset_discovery_response.RunAssetDiscoveryResponse.State): + The state of an asset discovery run. + duration (~.gp_duration.Duration): + The duration between asset discovery run + start and end + """ + + class State(proto.Enum): + r"""The state of an asset discovery run.""" + STATE_UNSPECIFIED = 0 + COMPLETED = 1 + SUPERSEDED = 2 + TERMINATED = 3 + + state = proto.Field(proto.ENUM, number=1, enum=State,) + + duration = proto.Field(proto.MESSAGE, number=2, message=gp_duration.Duration,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1beta1/types/security_marks.py b/google/cloud/securitycenter_v1beta1/types/security_marks.py new file mode 100644 index 00000000..7964b095 --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/types/security_marks.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1beta1", manifest={"SecurityMarks",}, +) + + +class SecurityMarks(proto.Message): + r"""User specified security marks that are attached to the parent + Security Command Center resource. Security marks are scoped + within a Security Command Center organization -- they can be + modified and viewed by all users who have proper permissions on + the organization. + + Attributes: + name (str): + The relative resource name of the SecurityMarks. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Examples: + "organizations/{organization_id}/assets/{asset_id}/securityMarks" + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks". + marks (Sequence[~.security_marks.SecurityMarks.MarksEntry]): + Mutable user specified security marks belonging to the + parent resource. Constraints are as follows: + + - Keys and values are treated as case insensitive + - Keys must be between 1 - 256 characters (inclusive) + - Keys must be letters, numbers, underscores, or dashes + - Values have leading and trailing whitespace trimmed, + remaining characters must be between 1 - 4096 characters + (inclusive) + """ + + name = proto.Field(proto.STRING, number=1) + + marks = proto.MapField(proto.STRING, proto.STRING, number=2) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py b/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py new file mode 100644 index 00000000..833f60fc --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py @@ -0,0 +1,862 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +from google.cloud.securitycenter_v1beta1.types import asset as gcs_asset +from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1beta1.types import ( + organization_settings as gcs_organization_settings, +) +from google.cloud.securitycenter_v1beta1.types import ( + security_marks as gcs_security_marks, +) +from google.cloud.securitycenter_v1beta1.types import source as gcs_source +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import field_mask_pb2 as gp_field_mask # type: ignore +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1beta1", + manifest={ + "CreateFindingRequest", + "CreateSourceRequest", + "GetOrganizationSettingsRequest", + "GetSourceRequest", + "GroupAssetsRequest", + "GroupAssetsResponse", + "GroupFindingsRequest", + "GroupFindingsResponse", + "GroupResult", + "ListSourcesRequest", + "ListSourcesResponse", + "ListAssetsRequest", + "ListAssetsResponse", + "ListFindingsRequest", + "ListFindingsResponse", + "SetFindingStateRequest", + "RunAssetDiscoveryRequest", + "UpdateFindingRequest", + "UpdateOrganizationSettingsRequest", + "UpdateSourceRequest", + "UpdateSecurityMarksRequest", + }, +) + + +class CreateFindingRequest(proto.Message): + r"""Request message for creating a finding. + + Attributes: + parent (str): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + finding_id (str): + Required. Unique identifier provided by the + client within the parent scope. It must be + alphanumeric and less than or equal to 32 + characters and greater than 0 characters in + length. + finding (~.gcs_finding.Finding): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output only + fields on this resource. + """ + + parent = proto.Field(proto.STRING, number=1) + + finding_id = proto.Field(proto.STRING, number=2) + + finding = proto.Field(proto.MESSAGE, number=3, message=gcs_finding.Finding,) + + +class CreateSourceRequest(proto.Message): + r"""Request message for creating a source. + + Attributes: + parent (str): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + source (~.gcs_source.Source): + Required. The Source being created, only the display_name + and description will be used. All other fields will be + ignored. + """ + + parent = proto.Field(proto.STRING, number=1) + + source = proto.Field(proto.MESSAGE, number=2, message=gcs_source.Source,) + + +class GetOrganizationSettingsRequest(proto.Message): + r"""Request message for getting organization settings. + + Attributes: + name (str): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + """ + + name = proto.Field(proto.STRING, number=1) + + +class GetSourceRequest(proto.Message): + r"""Request message for getting a source. + + Attributes: + name (str): + Required. Relative resource name of the source. Its format + is "organizations/[organization_id]/source/[source_id]". + """ + + name = proto.Field(proto.STRING, number=1) + + +class GroupAssetsRequest(proto.Message): + r"""Request message for grouping by assets. + + Attributes: + parent (str): + Required. Name of the organization to groupBy. Its format is + "organizations/[organization_id]". + filter (str): + Expression that defines the filter to apply across assets. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are not supported, and ``OR`` has higher + precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the Asset + resource. Examples include: + + - name + - security_center_properties.resource_name + - resource_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + For example, ``resource_properties.size = 100`` is a valid + filter string. + group_by (str): + Required. Expression that defines what assets fields to use + for grouping. The string value should follow SQL syntax: + comma separated list of fields. For example: + "security_center_properties.resource_project,security_center_properties.project". + + The following fields are supported when compare_duration is + not set: + + - security_center_properties.resource_project + - security_center_properties.resource_type + - security_center_properties.resource_parent + + The following fields are supported when compare_duration is + set: + + - security_center_properties.resource_type + compare_duration (~.duration.Duration): + When compare_duration is set, the Asset's "state" property + is updated to indicate whether the asset was added, removed, + or remained present during the compare_duration period of + time that precedes the read_time. This is the time between + (read_time - compare_duration) and read_time. + + The state value is derived based on the presence of the + asset at the two points in time. Intermediate state changes + between the two times don't affect the result. For example, + the results aren't affected if the asset is removed and + re-created again. + + Possible "state" values when compare_duration is specified: + + - "ADDED": indicates that the asset was not present before + compare_duration, but present at reference_time. + - "REMOVED": indicates that the asset was present at the + start of compare_duration, but not present at + reference_time. + - "ACTIVE": indicates that the asset was present at both + the start and the end of the time period defined by + compare_duration and reference_time. + + This field is ignored if ``state`` is not a field in + ``group_by``. + read_time (~.timestamp.Timestamp): + Time used as a reference point when filtering + assets. The filter is limited to assets existing + at the supplied time and their values are those + at that specific time. Absence of this field + will default to the API's version of NOW. + page_token (str): + The value returned by the last ``GroupAssetsResponse``; + indicates that this is a continuation of a prior + ``GroupAssets`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field(proto.STRING, number=1) + + filter = proto.Field(proto.STRING, number=2) + + group_by = proto.Field(proto.STRING, number=3) + + compare_duration = proto.Field(proto.MESSAGE, number=4, message=duration.Duration,) + + read_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) + + page_token = proto.Field(proto.STRING, number=7) + + page_size = proto.Field(proto.INT32, number=8) + + +class GroupAssetsResponse(proto.Message): + r"""Response message for grouping by assets. + + Attributes: + group_by_results (Sequence[~.securitycenter_service.GroupResult]): + Group results. There exists an element for + each existing unique combination of + property/values. The element contains a count + for the number of times those specific + property/values appear. + read_time (~.timestamp.Timestamp): + Time used for executing the groupBy request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + group_by_results = proto.RepeatedField( + proto.MESSAGE, number=1, message="GroupResult", + ) + + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + next_page_token = proto.Field(proto.STRING, number=3) + + +class GroupFindingsRequest(proto.Message): + r"""Request message for grouping by findings. + + Attributes: + parent (str): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]". To + groupBy across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/- + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are not supported, and ``OR`` has higher + precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - source_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + For example, ``source_properties.size = 100`` is a valid + filter string. + group_by (str): + Required. Expression that defines what assets fields to use + for grouping (including ``state``). The string value should + follow SQL syntax: comma separated list of fields. For + example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + read_time (~.timestamp.Timestamp): + Time used as a reference point when filtering + findings. The filter is limited to findings + existing at the supplied time and their values + are those at that specific time. Absence of this + field will default to the API's version of NOW. + page_token (str): + The value returned by the last ``GroupFindingsResponse``; + indicates that this is a continuation of a prior + ``GroupFindings`` call, and that the system should return + the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field(proto.STRING, number=1) + + filter = proto.Field(proto.STRING, number=2) + + group_by = proto.Field(proto.STRING, number=3) + + read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) + + page_token = proto.Field(proto.STRING, number=5) + + page_size = proto.Field(proto.INT32, number=6) + + +class GroupFindingsResponse(proto.Message): + r"""Response message for group by findings. + + Attributes: + group_by_results (Sequence[~.securitycenter_service.GroupResult]): + Group results. There exists an element for + each existing unique combination of + property/values. The element contains a count + for the number of times those specific + property/values appear. + read_time (~.timestamp.Timestamp): + Time used for executing the groupBy request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + group_by_results = proto.RepeatedField( + proto.MESSAGE, number=1, message="GroupResult", + ) + + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + next_page_token = proto.Field(proto.STRING, number=3) + + +class GroupResult(proto.Message): + r"""Result containing the properties and count of a groupBy + request. + + Attributes: + properties (Sequence[~.securitycenter_service.GroupResult.PropertiesEntry]): + Properties matching the groupBy fields in the + request. + count (int): + Total count of resources for the given + properties. + """ + + properties = proto.MapField( + proto.STRING, proto.MESSAGE, number=1, message=struct.Value, + ) + + count = proto.Field(proto.INT64, number=2) + + +class ListSourcesRequest(proto.Message): + r"""Request message for listing sources. + + Attributes: + parent (str): + Required. Resource name of the parent of sources to list. + Its format should be "organizations/[organization_id]". + page_token (str): + The value returned by the last ``ListSourcesResponse``; + indicates that this is a continuation of a prior + ``ListSources`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_token = proto.Field(proto.STRING, number=2) + + page_size = proto.Field(proto.INT32, number=7) + + +class ListSourcesResponse(proto.Message): + r"""Response message for listing sources. + + Attributes: + sources (Sequence[~.gcs_source.Source]): + Sources belonging to the requested parent. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + sources = proto.RepeatedField(proto.MESSAGE, number=1, message=gcs_source.Source,) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class ListAssetsRequest(proto.Message): + r"""Request message for listing assets. + + Attributes: + parent (str): + Required. Name of the organization assets should belong to. + Its format is "organizations/[organization_id]". + filter (str): + Expression that defines the filter to apply across assets. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are not supported, and ``OR`` has higher + precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the Asset + resource. Examples include: + + - name + - security_center_properties.resource_name + - resource_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + For example, ``resource_properties.size = 100`` is a valid + filter string. + order_by (str): + Expression that defines what fields and order to use for + sorting. The string value should follow SQL syntax: comma + separated list of fields. For example: + "name,resource_properties.a_property". The default sorting + order is ascending. To specify descending order for a field, + a suffix " desc" should be appended to the field name. For + example: "name desc,resource_properties.a_property". + Redundant space characters in the syntax are insignificant. + "name desc,resource_properties.a_property" and " name desc , + resource_properties.a_property " are equivalent. + read_time (~.timestamp.Timestamp): + Time used as a reference point when filtering + assets. The filter is limited to assets existing + at the supplied time and their values are those + at that specific time. Absence of this field + will default to the API's version of NOW. + compare_duration (~.duration.Duration): + When compare_duration is set, the ListAssetResult's "state" + attribute is updated to indicate whether the asset was + added, removed, or remained present during the + compare_duration period of time that precedes the read_time. + This is the time between (read_time - compare_duration) and + read_time. + + The state value is derived based on the presence of the + asset at the two points in time. Intermediate state changes + between the two times don't affect the result. For example, + the results aren't affected if the asset is removed and + re-created again. + + Possible "state" values when compare_duration is specified: + + - "ADDED": indicates that the asset was not present before + compare_duration, but present at read_time. + - "REMOVED": indicates that the asset was present at the + start of compare_duration, but not present at read_time. + - "ACTIVE": indicates that the asset was present at both + the start and the end of the time period defined by + compare_duration and read_time. + + If compare_duration is not specified, then the only possible + state is "UNUSED", which indicates that the asset is present + at read_time. + field_mask (~.gp_field_mask.FieldMask): + Optional. A field mask to specify the + ListAssetsResult fields to be listed in the + response. An empty field mask will list all + fields. + page_token (str): + The value returned by the last ``ListAssetsResponse``; + indicates that this is a continuation of a prior + ``ListAssets`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field(proto.STRING, number=1) + + filter = proto.Field(proto.STRING, number=2) + + order_by = proto.Field(proto.STRING, number=3) + + read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) + + compare_duration = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) + + field_mask = proto.Field(proto.MESSAGE, number=7, message=gp_field_mask.FieldMask,) + + page_token = proto.Field(proto.STRING, number=8) + + page_size = proto.Field(proto.INT32, number=9) + + +class ListAssetsResponse(proto.Message): + r"""Response message for listing assets. + + Attributes: + list_assets_results (Sequence[~.securitycenter_service.ListAssetsResponse.ListAssetsResult]): + Assets matching the list request. + read_time (~.timestamp.Timestamp): + Time used for executing the list request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of assets matching the + query. + """ + + class ListAssetsResult(proto.Message): + r"""Result containing the Asset and its State. + + Attributes: + asset (~.gcs_asset.Asset): + Asset matching the search request. + state (~.securitycenter_service.ListAssetsResponse.ListAssetsResult.State): + State of the asset. + """ + + class State(proto.Enum): + r"""State of the asset. + + When querying across two points in time this describes the change + between the two points: ADDED, REMOVED, or ACTIVE. If there was no + compare_duration supplied in the request the state should be: UNUSED + """ + STATE_UNSPECIFIED = 0 + UNUSED = 1 + ADDED = 2 + REMOVED = 3 + ACTIVE = 4 + + asset = proto.Field(proto.MESSAGE, number=1, message=gcs_asset.Asset,) + + state = proto.Field( + proto.ENUM, number=2, enum="ListAssetsResponse.ListAssetsResult.State", + ) + + @property + def raw_page(self): + return self + + list_assets_results = proto.RepeatedField( + proto.MESSAGE, number=1, message=ListAssetsResult, + ) + + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + next_page_token = proto.Field(proto.STRING, number=3) + + total_size = proto.Field(proto.INT32, number=4) + + +class ListFindingsRequest(proto.Message): + r"""Request message for listing findings. + + Attributes: + parent (str): + Required. Name of the source the findings belong to. Its + format is + "organizations/[organization_id]/sources/[source_id]". To + list across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/- + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are not supported, and ``OR`` has higher + precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - source_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + For example, ``source_properties.size = 100`` is a valid + filter string. + order_by (str): + Expression that defines what fields and order to use for + sorting. The string value should follow SQL syntax: comma + separated list of fields. For example: + "name,resource_properties.a_property". The default sorting + order is ascending. To specify descending order for a field, + a suffix " desc" should be appended to the field name. For + example: "name desc,source_properties.a_property". Redundant + space characters in the syntax are insignificant. "name + desc,source_properties.a_property" and " name desc , + source_properties.a_property " are equivalent. + read_time (~.timestamp.Timestamp): + Time used as a reference point when filtering + findings. The filter is limited to findings + existing at the supplied time and their values + are those at that specific time. Absence of this + field will default to the API's version of NOW. + field_mask (~.gp_field_mask.FieldMask): + Optional. A field mask to specify the Finding + fields to be listed in the response. An empty + field mask will list all fields. + page_token (str): + The value returned by the last ``ListFindingsResponse``; + indicates that this is a continuation of a prior + ``ListFindings`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field(proto.STRING, number=1) + + filter = proto.Field(proto.STRING, number=2) + + order_by = proto.Field(proto.STRING, number=3) + + read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) + + field_mask = proto.Field(proto.MESSAGE, number=5, message=gp_field_mask.FieldMask,) + + page_token = proto.Field(proto.STRING, number=6) + + page_size = proto.Field(proto.INT32, number=7) + + +class ListFindingsResponse(proto.Message): + r"""Response message for listing findings. + + Attributes: + findings (Sequence[~.gcs_finding.Finding]): + Findings matching the list request. + read_time (~.timestamp.Timestamp): + Time used for executing the list request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of findings matching the + query. + """ + + @property + def raw_page(self): + return self + + findings = proto.RepeatedField( + proto.MESSAGE, number=1, message=gcs_finding.Finding, + ) + + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + next_page_token = proto.Field(proto.STRING, number=3) + + total_size = proto.Field(proto.INT32, number=4) + + +class SetFindingStateRequest(proto.Message): + r"""Request message for updating a finding's state. + + Attributes: + name (str): + Required. The relative resource name of the finding. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + state (~.gcs_finding.Finding.State): + Required. The desired State of the finding. + start_time (~.timestamp.Timestamp): + Required. The time at which the updated state + takes effect. + """ + + name = proto.Field(proto.STRING, number=1) + + state = proto.Field(proto.ENUM, number=2, enum=gcs_finding.Finding.State,) + + start_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + + +class RunAssetDiscoveryRequest(proto.Message): + r"""Request message for running asset discovery for an + organization. + + Attributes: + parent (str): + Required. Name of the organization to run asset discovery + for. Its format is "organizations/[organization_id]". + """ + + parent = proto.Field(proto.STRING, number=1) + + +class UpdateFindingRequest(proto.Message): + r"""Request message for updating or creating a finding. + + Attributes: + finding (~.gcs_finding.Finding): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the name + must alphanumeric and less than or equal to 32 characters + and greater than 0 characters in length. + update_mask (~.gp_field_mask.FieldMask): + The FieldMask to use when updating the + finding resource. This field should not be + specified when creating a finding. + """ + + finding = proto.Field(proto.MESSAGE, number=1, message=gcs_finding.Finding,) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + + +class UpdateOrganizationSettingsRequest(proto.Message): + r"""Request message for updating an organization's settings. + + Attributes: + organization_settings (~.gcs_organization_settings.OrganizationSettings): + Required. The organization settings resource + to update. + update_mask (~.gp_field_mask.FieldMask): + The FieldMask to use when updating the + settings resource. + """ + + organization_settings = proto.Field( + proto.MESSAGE, number=1, message=gcs_organization_settings.OrganizationSettings, + ) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + + +class UpdateSourceRequest(proto.Message): + r"""Request message for updating a source. + + Attributes: + source (~.gcs_source.Source): + Required. The source resource to update. + update_mask (~.gp_field_mask.FieldMask): + The FieldMask to use when updating the source + resource. + """ + + source = proto.Field(proto.MESSAGE, number=1, message=gcs_source.Source,) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + + +class UpdateSecurityMarksRequest(proto.Message): + r"""Request message for updating a SecurityMarks resource. + + Attributes: + security_marks (~.gcs_security_marks.SecurityMarks): + Required. The security marks resource to + update. + update_mask (~.gp_field_mask.FieldMask): + The FieldMask to use when updating the + security marks resource. + start_time (~.timestamp.Timestamp): + The time at which the updated SecurityMarks + take effect. + """ + + security_marks = proto.Field( + proto.MESSAGE, number=1, message=gcs_security_marks.SecurityMarks, + ) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + + start_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1beta1/types/source.py b/google/cloud/securitycenter_v1beta1/types/source.py new file mode 100644 index 00000000..2546454f --- /dev/null +++ b/google/cloud/securitycenter_v1beta1/types/source.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1beta1", manifest={"Source",}, +) + + +class Source(proto.Message): + r"""Security Command Center finding source. A finding source + is an entity or a mechanism that can produce a finding. A source + is like a container of findings that come from the same scanner, + logger, monitor, etc. + + Attributes: + name (str): + The relative resource name of this source. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}". + display_name (str): + The source's display name. + A source's display name must be unique amongst + its siblings, for example, two sources with the + same parent can't share the same display name. + The display name must have a length between 1 + and 64 characters (inclusive). + description (str): + The description of the source (max of 1024 + characters). Example: + "Web Security Scanner is a web security scanner + for common vulnerabilities in App Engine + applications. It can automatically scan and + detect four common vulnerabilities, including + cross-site-scripting (XSS), Flash injection, + mixed content (HTTP in HTTPS), and + outdated/insecure libraries.". + """ + + name = proto.Field(proto.STRING, number=1) + + display_name = proto.Field(proto.STRING, number=2) + + description = proto.Field(proto.STRING, number=3) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/__init__.py b/google/cloud/securitycenter_v1p1beta1/__init__.py index 5e528124..27c3ed04 100644 --- a/google/cloud/securitycenter_v1p1beta1/__init__.py +++ b/google/cloud/securitycenter_v1p1beta1/__init__.py @@ -1,45 +1,95 @@ # -*- coding: utf-8 -*- -# + # Copyright 2020 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 +# 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 absolute_import -import sys -import warnings - -from google.cloud.securitycenter_v1p1beta1 import types -from google.cloud.securitycenter_v1p1beta1.gapic import enums -from google.cloud.securitycenter_v1p1beta1.gapic import security_center_client - - -if sys.version_info[:2] == (2, 7): - message = ( - "A future version of this library will drop support for Python 2.7. " - "More details about Python 2 support for Google Cloud Client Libraries " - "can be found at https://cloud.google.com/python/docs/python2-sunset/" - ) - warnings.warn(message, DeprecationWarning) - - -class SecurityCenterClient(security_center_client.SecurityCenterClient): - __doc__ = security_center_client.SecurityCenterClient.__doc__ - enums = enums +from .services.security_center import SecurityCenterClient +from .types.asset import Asset +from .types.finding import Finding +from .types.notification_config import NotificationConfig +from .types.notification_message import NotificationMessage +from .types.organization_settings import OrganizationSettings +from .types.resource import Resource +from .types.run_asset_discovery_response import RunAssetDiscoveryResponse +from .types.security_marks import SecurityMarks +from .types.securitycenter_service import CreateFindingRequest +from .types.securitycenter_service import CreateNotificationConfigRequest +from .types.securitycenter_service import CreateSourceRequest +from .types.securitycenter_service import DeleteNotificationConfigRequest +from .types.securitycenter_service import GetNotificationConfigRequest +from .types.securitycenter_service import GetOrganizationSettingsRequest +from .types.securitycenter_service import GetSourceRequest +from .types.securitycenter_service import GroupAssetsRequest +from .types.securitycenter_service import GroupAssetsResponse +from .types.securitycenter_service import GroupFindingsRequest +from .types.securitycenter_service import GroupFindingsResponse +from .types.securitycenter_service import GroupResult +from .types.securitycenter_service import ListAssetsRequest +from .types.securitycenter_service import ListAssetsResponse +from .types.securitycenter_service import ListFindingsRequest +from .types.securitycenter_service import ListFindingsResponse +from .types.securitycenter_service import ListNotificationConfigsRequest +from .types.securitycenter_service import ListNotificationConfigsResponse +from .types.securitycenter_service import ListSourcesRequest +from .types.securitycenter_service import ListSourcesResponse +from .types.securitycenter_service import RunAssetDiscoveryRequest +from .types.securitycenter_service import SetFindingStateRequest +from .types.securitycenter_service import UpdateFindingRequest +from .types.securitycenter_service import UpdateNotificationConfigRequest +from .types.securitycenter_service import UpdateOrganizationSettingsRequest +from .types.securitycenter_service import UpdateSecurityMarksRequest +from .types.securitycenter_service import UpdateSourceRequest +from .types.source import Source __all__ = ( - "enums", - "types", + "Asset", + "CreateFindingRequest", + "CreateNotificationConfigRequest", + "CreateSourceRequest", + "DeleteNotificationConfigRequest", + "Finding", + "GetNotificationConfigRequest", + "GetOrganizationSettingsRequest", + "GetSourceRequest", + "GroupAssetsRequest", + "GroupAssetsResponse", + "GroupFindingsRequest", + "GroupFindingsResponse", + "GroupResult", + "ListAssetsRequest", + "ListAssetsResponse", + "ListFindingsRequest", + "ListFindingsResponse", + "ListNotificationConfigsRequest", + "ListNotificationConfigsResponse", + "ListSourcesRequest", + "ListSourcesResponse", + "NotificationConfig", + "NotificationMessage", + "OrganizationSettings", + "Resource", + "RunAssetDiscoveryRequest", + "RunAssetDiscoveryResponse", + "SecurityMarks", + "SetFindingStateRequest", + "Source", + "UpdateFindingRequest", + "UpdateNotificationConfigRequest", + "UpdateOrganizationSettingsRequest", + "UpdateSecurityMarksRequest", + "UpdateSourceRequest", "SecurityCenterClient", ) diff --git a/google/cloud/securitycenter_v1p1beta1/gapic/security_center_client_config.py b/google/cloud/securitycenter_v1p1beta1/gapic/security_center_client_config.py index 1f6297b6..975998d8 100644 --- a/google/cloud/securitycenter_v1p1beta1/gapic/security_center_client_config.py +++ b/google/cloud/securitycenter_v1p1beta1/gapic/security_center_client_config.py @@ -2,174 +2,135 @@ "interfaces": { "google.cloud.securitycenter.v1p1beta1.SecurityCenter": { "retry_codes": { - "retry_policy_1_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "no_retry_2_codes": [], - "no_retry_codes": [], - "retry_policy_2_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "no_retry_1_codes": [], + "idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], + "non_idempotent": [], }, "retry_params": { - "retry_policy_1_params": { + "default": { "initial_retry_delay_millis": 100, "retry_delay_multiplier": 1.3, "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 60000, + "initial_rpc_timeout_millis": 20000, "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 60000, - }, - "retry_policy_2_params": { - "initial_retry_delay_millis": 100, - "retry_delay_multiplier": 1.3, - "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 480000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 480000, - "total_timeout_millis": 480000, - }, - "no_retry_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 0, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 0, - "total_timeout_millis": 0, - }, - "no_retry_1_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 60000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 60000, - "total_timeout_millis": 60000, - }, - "no_retry_2_params": { - "initial_retry_delay_millis": 0, - "retry_delay_multiplier": 0.0, - "max_retry_delay_millis": 0, - "initial_rpc_timeout_millis": 480000, - "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 480000, - "total_timeout_millis": 480000, - }, + "max_rpc_timeout_millis": 20000, + "total_timeout_millis": 600000, + } }, "methods": { "CreateSource": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "CreateFinding": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "CreateNotificationConfig": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "DeleteNotificationConfig": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "GetIamPolicy": { "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "GetNotificationConfig": { "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", + "retry_codes_name": "idempotent", + "retry_params_name": "default", }, "GetOrganizationSettings": { "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", + "retry_codes_name": "idempotent", + "retry_params_name": "default", }, "GetSource": { "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", + "retry_codes_name": "idempotent", + "retry_params_name": "default", }, "GroupAssets": { - "timeout_millis": 480000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "GroupFindings": { - "timeout_millis": 480000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "ListAssets": { - "timeout_millis": 480000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default", }, "ListFindings": { - "timeout_millis": 480000, - "retry_codes_name": "retry_policy_2_codes", - "retry_params_name": "retry_policy_2_params", + "timeout_millis": 60000, + "retry_codes_name": "idempotent", + "retry_params_name": "default", }, "ListNotificationConfigs": { "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", + "retry_codes_name": "idempotent", + "retry_params_name": "default", }, "ListSources": { "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", + "retry_codes_name": "idempotent", + "retry_params_name": "default", }, "RunAssetDiscovery": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "SetFindingState": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "SetIamPolicy": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "TestIamPermissions": { "timeout_millis": 60000, - "retry_codes_name": "retry_policy_1_codes", - "retry_params_name": "retry_policy_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "UpdateFinding": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "UpdateNotificationConfig": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "UpdateOrganizationSettings": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "UpdateSource": { "timeout_millis": 60000, - "retry_codes_name": "no_retry_1_codes", - "retry_params_name": "no_retry_1_params", + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, "UpdateSecurityMarks": { - "timeout_millis": 480000, - "retry_codes_name": "no_retry_2_codes", - "retry_params_name": "no_retry_2_params", + "timeout_millis": 60000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default", }, }, } diff --git a/google/cloud/securitycenter_v1p1beta1/py.typed b/google/cloud/securitycenter_v1p1beta1/py.typed new file mode 100644 index 00000000..23a44fc7 --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/py.typed @@ -0,0 +1,2 @@ +# Marker file for PEP 561. +# The google-cloud-securitycenter package uses inline types. diff --git a/google/cloud/securitycenter_v1p1beta1/services/__init__.py b/google/cloud/securitycenter_v1p1beta1/services/__init__.py new file mode 100644 index 00000000..42ffdf2b --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/services/__init__.py @@ -0,0 +1,16 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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. +# diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py new file mode 100644 index 00000000..6250349b --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 SecurityCenterClient +from .async_client import SecurityCenterAsyncClient + +__all__ = ( + "SecurityCenterClient", + "SecurityCenterAsyncClient", +) diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py new file mode 100644 index 00000000..4b652db0 --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py @@ -0,0 +1,2317 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 +import functools +import re +from typing import Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation +from google.api_core import operation_async +from google.cloud.securitycenter_v1p1beta1.services.security_center import pagers +from google.cloud.securitycenter_v1p1beta1.types import finding +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import ( + notification_config as gcs_notification_config, +) +from google.cloud.securitycenter_v1p1beta1.types import organization_settings +from google.cloud.securitycenter_v1p1beta1.types import ( + organization_settings as gcs_organization_settings, +) +from google.cloud.securitycenter_v1p1beta1.types import run_asset_discovery_response +from google.cloud.securitycenter_v1p1beta1.types import security_marks +from google.cloud.securitycenter_v1p1beta1.types import ( + security_marks as gcs_security_marks, +) +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + +from .transports.base import SecurityCenterTransport +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport +from .client import SecurityCenterClient + + +class SecurityCenterAsyncClient: + """V1p1Beta1 APIs for Security Center service.""" + + _client: SecurityCenterClient + + DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT + DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + + security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + + organization_settings_path = staticmethod( + SecurityCenterClient.organization_settings_path + ) + + source_path = staticmethod(SecurityCenterClient.source_path) + + notification_config_path = staticmethod( + SecurityCenterClient.notification_config_path + ) + + finding_path = staticmethod(SecurityCenterClient.finding_path) + + from_service_account_file = SecurityCenterClient.from_service_account_file + from_service_account_json = from_service_account_file + + get_transport_class = functools.partial( + type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient) + ) + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, SecurityCenterTransport] = "grpc_asyncio", + client_options: ClientOptions = None, + ) -> None: + """Instantiate the security center 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. + transport (Union[str, ~.SecurityCenterTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport + creation failed for any reason. + """ + + self._client = SecurityCenterClient( + credentials=credentials, transport=transport, client_options=client_options, + ) + + async def create_source( + self, + request: securitycenter_service.CreateSourceRequest = None, + *, + parent: str = None, + source: gcs_source.Source = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a source. + + Args: + request (:class:`~.securitycenter_service.CreateSourceRequest`): + The request object. Request message for creating a + source. + parent (:class:`str`): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (:class:`~.gcs_source.Source`): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + This corresponds to the ``source`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, source]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.CreateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_source, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def create_finding( + self, + request: securitycenter_service.CreateFindingRequest = None, + *, + parent: str = None, + finding_id: str = None, + finding: gcs_finding.Finding = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Args: + request (:class:`~.securitycenter_service.CreateFindingRequest`): + The request object. Request message for creating a + finding. + parent (:class:`str`): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + It must be alphanumeric and less than or + equal to 32 characters and greater than + 0 characters in length. + This corresponds to the ``finding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (:class:`~.gcs_finding.Finding`): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + This corresponds to the ``finding`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_finding.Finding: + Security Command Center finding. + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, finding_id, finding]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.CreateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if finding_id is not None: + request.finding_id = finding_id + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_finding, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def create_notification_config( + self, + request: securitycenter_service.CreateNotificationConfigRequest = None, + *, + parent: str = None, + config_id: str = None, + notification_config: gcs_notification_config.NotificationConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Creates a notification config. + + Args: + request (:class:`~.securitycenter_service.CreateNotificationConfigRequest`): + The request object. Request message for creating a + notification config. + parent (:class:`str`): + Required. Resource name of the new notification config's + parent. Its format is "organizations/[organization_id]". + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config_id (:class:`str`): + Required. + Unique identifier provided by the client + within the parent scope. It must be + between 1 and 128 characters, and + contains alphanumeric characters, + underscores or hyphens only. + This corresponds to the ``config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notification_config (:class:`~.gcs_notification_config.NotificationConfig`): + Required. The notification config + being created. The name and the service + account will be ignored as they are both + output only fields on this resource. + This corresponds to the ``notification_config`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_notification_config.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, config_id, notification_config]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.CreateNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if config_id is not None: + request.config_id = config_id + if notification_config is not None: + request.notification_config = notification_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.create_notification_config, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def delete_notification_config( + self, + request: securitycenter_service.DeleteNotificationConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a notification config. + + Args: + request (:class:`~.securitycenter_service.DeleteNotificationConfigRequest`): + The request object. Request message for deleting a + notification config. + name (:class:`str`): + Required. Name of the notification config to delete. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_id]". + This corresponds to the ``name`` 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.DeleteNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.delete_notification_config, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + await rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + async def get_iam_policy( + self, + request: iam_policy.GetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Gets the access control policy on the specified + Source. + + Args: + request (:class:`~.iam_policy.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + This corresponds to the ``resource`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([resource]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.GetIamPolicyRequest(**request) + + elif not request: + request = iam_policy.GetIamPolicyRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_iam_policy, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_notification_config( + self, + request: securitycenter_service.GetNotificationConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> notification_config.NotificationConfig: + r"""Gets a notification config. + + Args: + request (:class:`~.securitycenter_service.GetNotificationConfigRequest`): + The request object. Request message for getting a + notification config. + name (:class:`str`): + Required. Name of the notification config to get. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_id]". + This corresponds to the ``name`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.notification_config.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.GetNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_notification_config, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_organization_settings( + self, + request: securitycenter_service.GetOrganizationSettingsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> organization_settings.OrganizationSettings: + r"""Gets the settings for an organization. + + Args: + request (:class:`~.securitycenter_service.GetOrganizationSettingsRequest`): + The request object. Request message for getting + organization settings. + name (:class:`str`): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + This corresponds to the ``name`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.organization_settings.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.GetOrganizationSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_organization_settings, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def get_source( + self, + request: securitycenter_service.GetSourceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Gets a source. + + Args: + request (:class:`~.securitycenter_service.GetSourceRequest`): + The request object. Request message for getting a + source. + name (:class:`str`): + Required. Relative resource name of the source. Its + format is + "organizations/[organization_id]/source/[source_id]". + This corresponds to the ``name`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.GetSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.get_source, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def group_assets( + self, + request: securitycenter_service.GroupAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupAssetsAsyncPager: + r"""Filters an organization's assets and groups them by + their specified properties. + + Args: + request (:class:`~.securitycenter_service.GroupAssetsRequest`): + The request object. Request message for grouping by + assets. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.GroupAssetsAsyncPager: + Response message for grouping by + assets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + + request = securitycenter_service.GroupAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.group_assets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.GroupAssetsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def group_findings( + self, + request: securitycenter_service.GroupFindingsRequest = None, + *, + parent: str = None, + group_by: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsAsyncPager: + r"""Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: + /v1p1beta1/organizations/{organization_id}/sources/-/findings + + Args: + request (:class:`~.securitycenter_service.GroupFindingsRequest`): + The request object. Request message for grouping by + findings. + parent (:class:`str`): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]". + To groupBy across all sources provide a source_id of + ``-``. For example: + organizations/{organization_id}/sources/- + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (:class:`str`): + Required. Expression that defines what assets fields to + use for grouping (including ``state_change``). The + string value should follow SQL syntax: comma separated + list of fields. For example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + + The following fields are supported when compare_duration + is set: + + - state_change + This corresponds to the ``group_by`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.GroupFindingsAsyncPager: + Response message for group by + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, group_by]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.GroupFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.group_findings, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.GroupFindingsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_assets( + self, + request: securitycenter_service.ListAssetsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsAsyncPager: + r"""Lists an organization's assets. + + Args: + request (:class:`~.securitycenter_service.ListAssetsRequest`): + The request object. Request message for listing assets. + parent (:class:`str`): + Required. Name of the organization assets should belong + to. Its format is "organizations/[organization_id]". + This corresponds to the ``parent`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListAssetsAsyncPager: + Response message for listing assets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.ListAssetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_assets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListAssetsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_findings( + self, + request: securitycenter_service.ListFindingsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFindingsAsyncPager: + r"""Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1p1beta1/organizations/{organization_id}/sources/-/findings + + Args: + request (:class:`~.securitycenter_service.ListFindingsRequest`): + The request object. Request message for listing + findings. + parent (:class:`str`): + Required. Name of the source the findings belong to. Its + format is + "organizations/[organization_id]/sources/[source_id]". + To list across all sources provide a source_id of ``-``. + For example: organizations/{organization_id}/sources/- + This corresponds to the ``parent`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListFindingsAsyncPager: + Response message for listing + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.ListFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_findings, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListFindingsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_notification_configs( + self, + request: securitycenter_service.ListNotificationConfigsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListNotificationConfigsAsyncPager: + r"""Lists notification configs. + + Args: + request (:class:`~.securitycenter_service.ListNotificationConfigsRequest`): + The request object. Request message for listing + notification configs. + parent (:class:`str`): + Required. Name of the organization to list notification + configs. Its format is + "organizations/[organization_id]". + This corresponds to the ``parent`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListNotificationConfigsAsyncPager: + Response message for listing + notification configs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.ListNotificationConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_notification_configs, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListNotificationConfigsAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def list_sources( + self, + request: securitycenter_service.ListSourcesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSourcesAsyncPager: + r"""Lists all sources belonging to an organization. + + Args: + request (:class:`~.securitycenter_service.ListSourcesRequest`): + The request object. Request message for listing sources. + parent (:class:`str`): + Required. Resource name of the parent of sources to + list. Its format should be + "organizations/[organization_id]". + This corresponds to the ``parent`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListSourcesAsyncPager: + Response message for listing sources. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.ListSourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.list_sources, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__aiter__` convenience method. + response = pagers.ListSourcesAsyncPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + async def run_asset_discovery( + self, + request: securitycenter_service.RunAssetDiscoveryRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation_async.AsyncOperation: + r"""Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Args: + request (:class:`~.securitycenter_service.RunAssetDiscoveryRequest`): + The request object. Request message for running asset + discovery for an organization. + parent (:class:`str`): + Required. Name of the organization to run asset + discovery for. Its format is + "organizations/[organization_id]". + This corresponds to the ``parent`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation_async.AsyncOperation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.run_asset_discovery_response.RunAssetDiscoveryResponse``: + Response of asset discovery run + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.RunAssetDiscoveryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.run_asset_discovery, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation_async.from_gapic( + response, + self._client._transport.operations_client, + run_asset_discovery_response.RunAssetDiscoveryResponse, + metadata_type=empty.Empty, + ) + + # Done; return the response. + return response + + async def set_finding_state( + self, + request: securitycenter_service.SetFindingStateRequest = None, + *, + name: str = None, + state: finding.Finding.State = None, + start_time: timestamp.Timestamp = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of a finding. + + Args: + request (:class:`~.securitycenter_service.SetFindingStateRequest`): + The request object. Request message for updating a + finding's state. + name (:class:`str`): + Required. The relative resource name of the finding. + See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (:class:`~.finding.Finding.State`): + Required. The desired State of the + finding. + This corresponds to the ``state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + start_time (:class:`~.timestamp.Timestamp`): + Required. The time at which the + updated state takes effect. + This corresponds to the ``start_time`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.finding.Finding: + Security Command Center finding. + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name, state, start_time]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.SetFindingStateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if state is not None: + request.state = state + if start_time is not None: + request.start_time = start_time + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_finding_state, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def set_iam_policy( + self, + request: iam_policy.SetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Sets the access control policy on the specified + Source. + + Args: + request (:class:`~.iam_policy.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + This corresponds to the ``resource`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([resource]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.SetIamPolicyRequest(**request) + + elif not request: + request = iam_policy.SetIamPolicyRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.set_iam_policy, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def test_iam_permissions( + self, + request: iam_policy.TestIamPermissionsRequest = None, + *, + resource: str = None, + permissions: Sequence[str] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy.TestIamPermissionsResponse: + r"""Returns the permissions that a caller has on the + specified source. + + Args: + request (:class:`~.iam_policy.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`Sequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + This corresponds to the ``permissions`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.iam_policy.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([resource, permissions]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.TestIamPermissionsRequest(**request) + + elif not request: + request = iam_policy.TestIamPermissionsRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.resource = resource + + if permissions: + request.permissions.extend(permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.test_iam_permissions, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_finding( + self, + request: securitycenter_service.UpdateFindingRequest = None, + *, + finding: gcs_finding.Finding = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Args: + request (:class:`~.securitycenter_service.UpdateFindingRequest`): + The request object. Request message for updating or + creating a finding. + finding (:class:`~.gcs_finding.Finding`): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must be alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + The FieldMask to use when updating the finding resource. + This field should not be specified when creating a + finding. + + When updating a finding, an empty mask is treated as + updating all mutable fields and replacing + source_properties. Individual source_properties can be + added/updated by using "source_properties." in the field + mask. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_finding.Finding: + Security Command Center finding. + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([finding, update_mask]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.UpdateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if finding is not None: + request.finding = finding + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.update_finding, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("finding.name", request.finding.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_notification_config( + self, + request: securitycenter_service.UpdateNotificationConfigRequest = None, + *, + notification_config: gcs_notification_config.NotificationConfig = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Args: + request (:class:`~.securitycenter_service.UpdateNotificationConfigRequest`): + The request object. Request message for updating a + notification config. + notification_config (:class:`~.gcs_notification_config.NotificationConfig`): + Required. The notification config to + update. + This corresponds to the ``notification_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + The FieldMask to use when updating + the notification config. + If empty all mutable fields will be + updated. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_notification_config.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([notification_config, update_mask]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.UpdateNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if notification_config is not None: + request.notification_config = notification_config + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.update_notification_config, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("notification_config.name", request.notification_config.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_organization_settings( + self, + request: securitycenter_service.UpdateOrganizationSettingsRequest = None, + *, + organization_settings: gcs_organization_settings.OrganizationSettings = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Updates an organization's settings. + + Args: + request (:class:`~.securitycenter_service.UpdateOrganizationSettingsRequest`): + The request object. Request message for updating an + organization's settings. + organization_settings (:class:`~.gcs_organization_settings.OrganizationSettings`): + Required. The organization settings + resource to update. + This corresponds to the ``organization_settings`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_organization_settings.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([organization_settings]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.UpdateOrganizationSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if organization_settings is not None: + request.organization_settings = organization_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method_async.wrap_method( + self._client._transport.update_organization_settings, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("organization_settings.name", request.organization_settings.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_source( + self, + request: securitycenter_service.UpdateSourceRequest = None, + *, + source: gcs_source.Source = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Updates a source. + + Args: + request (:class:`~.securitycenter_service.UpdateSourceRequest`): + The request object. Request message for updating a + source. + source (:class:`~.gcs_source.Source`): + Required. The source resource to + update. + This corresponds to the ``source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + The FieldMask to use when updating + the source resource. + If empty all mutable fields will be + updated. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([source, update_mask]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.UpdateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if source is not None: + request.source = source + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.update_source, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("source.name", request.source.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + async def update_security_marks( + self, + request: securitycenter_service.UpdateSecurityMarksRequest = None, + *, + security_marks: gcs_security_marks.SecurityMarks = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. + + Args: + request (:class:`~.securitycenter_service.UpdateSecurityMarksRequest`): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (:class:`~.gcs_security_marks.SecurityMarks`): + Required. The security marks resource + to update. + This corresponds to the ``security_marks`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + The FieldMask to use when updating the security marks + resource. + + The field mask must not contain duplicate fields. If + empty or set to "marks", all marks will be replaced. + Individual marks can be updated using + "marks.". + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_security_marks.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([security_marks, update_mask]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.UpdateSecurityMarksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if security_marks is not None: + request.security_marks = security_marks + 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 = gapic_v1.method_async.wrap_method( + self._client._transport.update_security_marks, + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_marks.name", request.security_marks.name),) + ), + ) + + # Send the request. + response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-securitycenter", + ).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +__all__ = ("SecurityCenterAsyncClient",) diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py new file mode 100644 index 00000000..eddf3f24 --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py @@ -0,0 +1,2507 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 +import os +import re +from typing import Callable, Dict, Sequence, Tuple, Type, Union +import pkg_resources + +import google.api_core.client_options as ClientOptions # type: ignore +from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport import mtls # type: ignore +from google.auth.exceptions import MutualTLSChannelError # type: ignore +from google.oauth2 import service_account # type: ignore + +from google.api_core import operation +from google.api_core import operation_async +from google.cloud.securitycenter_v1p1beta1.services.security_center import pagers +from google.cloud.securitycenter_v1p1beta1.types import finding +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import ( + notification_config as gcs_notification_config, +) +from google.cloud.securitycenter_v1p1beta1.types import organization_settings +from google.cloud.securitycenter_v1p1beta1.types import ( + organization_settings as gcs_organization_settings, +) +from google.cloud.securitycenter_v1p1beta1.types import run_asset_discovery_response +from google.cloud.securitycenter_v1p1beta1.types import security_marks +from google.cloud.securitycenter_v1p1beta1.types import ( + security_marks as gcs_security_marks, +) +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore +from google.protobuf import field_mask_pb2 as field_mask # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + +from .transports.base import SecurityCenterTransport +from .transports.grpc import SecurityCenterGrpcTransport +from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport + + +class SecurityCenterClientMeta(type): + """Metaclass for the SecurityCenter 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[SecurityCenterTransport]] + _transport_registry["grpc"] = SecurityCenterGrpcTransport + _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport + + def get_transport_class(cls, label: str = None,) -> Type[SecurityCenterTransport]: + """Return 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 SecurityCenterClient(metaclass=SecurityCenterClientMeta): + """V1p1Beta1 APIs for Security Center service.""" + + @staticmethod + def _get_default_mtls_endpoint(api_endpoint): + """Convert 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") + + DEFAULT_ENDPOINT = "securitycenter.googleapis.com" + DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore + DEFAULT_ENDPOINT + ) + + @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: + {@api.name}: 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 + + @staticmethod + def finding_path(organization: str, source: str, finding: str,) -> str: + """Return a fully-qualified finding string.""" + return "organizations/{organization}/sources/{source}/findings/{finding}".format( + organization=organization, source=source, finding=finding, + ) + + @staticmethod + def parse_finding_path(path: str) -> Dict[str, str]: + """Parse a finding path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def notification_config_path(organization: str, notification_config: str,) -> str: + """Return a fully-qualified notification_config string.""" + return "organizations/{organization}/notificationConfigs/{notification_config}".format( + organization=organization, notification_config=notification_config, + ) + + @staticmethod + def parse_notification_config_path(path: str) -> Dict[str, str]: + """Parse a notification_config path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/notificationConfigs/(?P.+?)$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def organization_settings_path(organization: str,) -> str: + """Return a fully-qualified organization_settings string.""" + return "organizations/{organization}/organizationSettings".format( + organization=organization, + ) + + @staticmethod + def parse_organization_settings_path(path: str) -> Dict[str, str]: + """Parse a organization_settings path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/organizationSettings$", path + ) + return m.groupdict() if m else {} + + @staticmethod + def security_marks_path(organization: str, asset: str,) -> str: + """Return a fully-qualified security_marks string.""" + return "organizations/{organization}/assets/{asset}/securityMarks".format( + organization=organization, asset=asset, + ) + + @staticmethod + def parse_security_marks_path(path: str) -> Dict[str, str]: + """Parse a security_marks path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", + path, + ) + return m.groupdict() if m else {} + + @staticmethod + def source_path(organization: str, source: str,) -> str: + """Return a fully-qualified source string.""" + return "organizations/{organization}/sources/{source}".format( + organization=organization, source=source, + ) + + @staticmethod + def parse_source_path(path: str) -> Dict[str, str]: + """Parse a source path into its component segments.""" + m = re.match( + r"^organizations/(?P.+?)/sources/(?P.+?)$", path + ) + return m.groupdict() if m else {} + + def __init__( + self, + *, + credentials: credentials.Credentials = None, + transport: Union[str, SecurityCenterTransport] = None, + client_options: ClientOptions = None, + ) -> None: + """Instantiate the security center 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. + transport (Union[str, ~.SecurityCenterTransport]): The + transport to use. If set to None, a transport is chosen + automatically. + client_options (ClientOptions): Custom options for the client. It + won't take effect if a ``transport`` instance is provided. + (1) The ``api_endpoint`` property can be used to override the + default endpoint provided by the client. GOOGLE_API_USE_MTLS + environment variable can also be used to override the endpoint: + "always" (always use the default mTLS endpoint), "never" (always + use the default regular endpoint, this is the default value for + the environment variable) and "auto" (auto switch to the default + mTLS endpoint if client SSL credentials is present). However, + the ``api_endpoint`` property takes precedence if provided. + (2) The ``client_cert_source`` property is used to provide client + SSL credentials for mutual TLS transport. If not provided, the + default SSL credentials will be used if present. + + Raises: + google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport + creation failed for any reason. + """ + if isinstance(client_options, dict): + client_options = ClientOptions.from_dict(client_options) + if client_options is None: + client_options = ClientOptions.ClientOptions() + + if client_options.api_endpoint is None: + use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") + if use_mtls_env == "never": + client_options.api_endpoint = self.DEFAULT_ENDPOINT + elif use_mtls_env == "always": + client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT + elif use_mtls_env == "auto": + has_client_cert_source = ( + client_options.client_cert_source is not None + or mtls.has_default_client_cert_source() + ) + client_options.api_endpoint = ( + self.DEFAULT_MTLS_ENDPOINT + if has_client_cert_source + else self.DEFAULT_ENDPOINT + ) + else: + raise MutualTLSChannelError( + "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always" + ) + + # Save or instantiate the transport. + # Ordinarily, we provide the transport, but allowing a custom transport + # instance provides an extensibility point for unusual situations. + if isinstance(transport, SecurityCenterTransport): + # transport is a SecurityCenterTransport instance. + if credentials or client_options.credentials_file: + raise ValueError( + "When providing a transport instance, " + "provide its credentials directly." + ) + if client_options.scopes: + raise ValueError( + "When providing a transport instance, " + "provide its scopes directly." + ) + self._transport = transport + else: + Transport = type(self).get_transport_class(transport) + self._transport = Transport( + credentials=credentials, + credentials_file=client_options.credentials_file, + host=client_options.api_endpoint, + scopes=client_options.scopes, + api_mtls_endpoint=client_options.api_endpoint, + client_cert_source=client_options.client_cert_source, + quota_project_id=client_options.quota_project_id, + ) + + def create_source( + self, + request: securitycenter_service.CreateSourceRequest = None, + *, + parent: str = None, + source: gcs_source.Source = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Creates a source. + + Args: + request (:class:`~.securitycenter_service.CreateSourceRequest`): + The request object. Request message for creating a + source. + parent (:class:`str`): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + source (:class:`~.gcs_source.Source`): + Required. The Source being created, only the + display_name and description will be used. All other + fields will be ignored. + This corresponds to the ``source`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, source]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.CreateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if source is not None: + request.source = source + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.create_source, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def create_finding( + self, + request: securitycenter_service.CreateFindingRequest = None, + *, + parent: str = None, + finding_id: str = None, + finding: gcs_finding.Finding = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Args: + request (:class:`~.securitycenter_service.CreateFindingRequest`): + The request object. Request message for creating a + finding. + parent (:class:`str`): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding_id (:class:`str`): + Required. Unique identifier provided + by the client within the parent scope. + It must be alphanumeric and less than or + equal to 32 characters and greater than + 0 characters in length. + This corresponds to the ``finding_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + finding (:class:`~.gcs_finding.Finding`): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output + only fields on this resource. + This corresponds to the ``finding`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_finding.Finding: + Security Command Center finding. + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, finding_id, finding]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.CreateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if finding_id is not None: + request.finding_id = finding_id + if finding is not None: + request.finding = finding + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.create_finding, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def create_notification_config( + self, + request: securitycenter_service.CreateNotificationConfigRequest = None, + *, + parent: str = None, + config_id: str = None, + notification_config: gcs_notification_config.NotificationConfig = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Creates a notification config. + + Args: + request (:class:`~.securitycenter_service.CreateNotificationConfigRequest`): + The request object. Request message for creating a + notification config. + parent (:class:`str`): + Required. Resource name of the new notification config's + parent. Its format is "organizations/[organization_id]". + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + config_id (:class:`str`): + Required. + Unique identifier provided by the client + within the parent scope. It must be + between 1 and 128 characters, and + contains alphanumeric characters, + underscores or hyphens only. + This corresponds to the ``config_id`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + notification_config (:class:`~.gcs_notification_config.NotificationConfig`): + Required. The notification config + being created. The name and the service + account will be ignored as they are both + output only fields on this resource. + This corresponds to the ``notification_config`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_notification_config.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, config_id, notification_config]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.CreateNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if config_id is not None: + request.config_id = config_id + if notification_config is not None: + request.notification_config = notification_config + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.create_notification_config, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def delete_notification_config( + self, + request: securitycenter_service.DeleteNotificationConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> None: + r"""Deletes a notification config. + + Args: + request (:class:`~.securitycenter_service.DeleteNotificationConfigRequest`): + The request object. Request message for deleting a + notification config. + name (:class:`str`): + Required. Name of the notification config to delete. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_id]". + This corresponds to the ``name`` 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, str]]): Strings which should be + sent along with the request as metadata. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.DeleteNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.delete_notification_config, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + rpc( + request, retry=retry, timeout=timeout, metadata=metadata, + ) + + def get_iam_policy( + self, + request: iam_policy.GetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Gets the access control policy on the specified + Source. + + Args: + request (:class:`~.iam_policy.GetIamPolicyRequest`): + The request object. Request message for `GetIamPolicy` + method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being requested. See the + operation documentation for the + appropriate value for this field. + This corresponds to the ``resource`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([resource]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.GetIamPolicyRequest(**request) + + elif not request: + request = iam_policy.GetIamPolicyRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_iam_policy, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_notification_config( + self, + request: securitycenter_service.GetNotificationConfigRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> notification_config.NotificationConfig: + r"""Gets a notification config. + + Args: + request (:class:`~.securitycenter_service.GetNotificationConfigRequest`): + The request object. Request message for getting a + notification config. + name (:class:`str`): + Required. Name of the notification config to get. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_id]". + This corresponds to the ``name`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.notification_config.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.GetNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_notification_config, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_organization_settings( + self, + request: securitycenter_service.GetOrganizationSettingsRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> organization_settings.OrganizationSettings: + r"""Gets the settings for an organization. + + Args: + request (:class:`~.securitycenter_service.GetOrganizationSettingsRequest`): + The request object. Request message for getting + organization settings. + name (:class:`str`): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + This corresponds to the ``name`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.organization_settings.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.GetOrganizationSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_organization_settings, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def get_source( + self, + request: securitycenter_service.GetSourceRequest = None, + *, + name: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> source.Source: + r"""Gets a source. + + Args: + request (:class:`~.securitycenter_service.GetSourceRequest`): + The request object. Request message for getting a + source. + name (:class:`str`): + Required. Relative resource name of the source. Its + format is + "organizations/[organization_id]/source/[source_id]". + This corresponds to the ``name`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.GetSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.get_source, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def group_assets( + self, + request: securitycenter_service.GroupAssetsRequest = None, + *, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupAssetsPager: + r"""Filters an organization's assets and groups them by + their specified properties. + + Args: + request (:class:`~.securitycenter_service.GroupAssetsRequest`): + The request object. Request message for grouping by + assets. + + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.GroupAssetsPager: + Response message for grouping by + assets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + + request = securitycenter_service.GroupAssetsRequest(request) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.group_assets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.GroupAssetsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def group_findings( + self, + request: securitycenter_service.GroupFindingsRequest = None, + *, + parent: str = None, + group_by: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.GroupFindingsPager: + r"""Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: + /v1p1beta1/organizations/{organization_id}/sources/-/findings + + Args: + request (:class:`~.securitycenter_service.GroupFindingsRequest`): + The request object. Request message for grouping by + findings. + parent (:class:`str`): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]". + To groupBy across all sources provide a source_id of + ``-``. For example: + organizations/{organization_id}/sources/- + This corresponds to the ``parent`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + group_by (:class:`str`): + Required. Expression that defines what assets fields to + use for grouping (including ``state_change``). The + string value should follow SQL syntax: comma separated + list of fields. For example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + + The following fields are supported when compare_duration + is set: + + - state_change + This corresponds to the ``group_by`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.GroupFindingsPager: + Response message for group by + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent, group_by]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.GroupFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.group_findings, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.GroupFindingsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def list_assets( + self, + request: securitycenter_service.ListAssetsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListAssetsPager: + r"""Lists an organization's assets. + + Args: + request (:class:`~.securitycenter_service.ListAssetsRequest`): + The request object. Request message for listing assets. + parent (:class:`str`): + Required. Name of the organization assets should belong + to. Its format is "organizations/[organization_id]". + This corresponds to the ``parent`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListAssetsPager: + Response message for listing assets. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.ListAssetsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_assets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListAssetsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def list_findings( + self, + request: securitycenter_service.ListFindingsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListFindingsPager: + r"""Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1p1beta1/organizations/{organization_id}/sources/-/findings + + Args: + request (:class:`~.securitycenter_service.ListFindingsRequest`): + The request object. Request message for listing + findings. + parent (:class:`str`): + Required. Name of the source the findings belong to. Its + format is + "organizations/[organization_id]/sources/[source_id]". + To list across all sources provide a source_id of ``-``. + For example: organizations/{organization_id}/sources/- + This corresponds to the ``parent`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListFindingsPager: + Response message for listing + findings. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.ListFindingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_findings, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListFindingsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def list_notification_configs( + self, + request: securitycenter_service.ListNotificationConfigsRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListNotificationConfigsPager: + r"""Lists notification configs. + + Args: + request (:class:`~.securitycenter_service.ListNotificationConfigsRequest`): + The request object. Request message for listing + notification configs. + parent (:class:`str`): + Required. Name of the organization to list notification + configs. Its format is + "organizations/[organization_id]". + This corresponds to the ``parent`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListNotificationConfigsPager: + Response message for listing + notification configs. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.ListNotificationConfigsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_notification_configs, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListNotificationConfigsPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def list_sources( + self, + request: securitycenter_service.ListSourcesRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> pagers.ListSourcesPager: + r"""Lists all sources belonging to an organization. + + Args: + request (:class:`~.securitycenter_service.ListSourcesRequest`): + The request object. Request message for listing sources. + parent (:class:`str`): + Required. Resource name of the parent of sources to + list. Its format should be + "organizations/[organization_id]". + This corresponds to the ``parent`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.pagers.ListSourcesPager: + Response message for listing sources. + Iterating over this object will yield + results and resolve additional pages + automatically. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.ListSourcesRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.list_sources, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # This method is paged; wrap the response in a pager, which provides + # an `__iter__` convenience method. + response = pagers.ListSourcesPager( + method=rpc, request=request, response=response, metadata=metadata, + ) + + # Done; return the response. + return response + + def run_asset_discovery( + self, + request: securitycenter_service.RunAssetDiscoveryRequest = None, + *, + parent: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> operation.Operation: + r"""Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Args: + request (:class:`~.securitycenter_service.RunAssetDiscoveryRequest`): + The request object. Request message for running asset + discovery for an organization. + parent (:class:`str`): + Required. Name of the organization to run asset + discovery for. Its format is + "organizations/[organization_id]". + This corresponds to the ``parent`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.operation.Operation: + An object representing a long-running operation. + + The result type for the operation will be + :class:``~.run_asset_discovery_response.RunAssetDiscoveryResponse``: + Response of asset discovery run + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([parent]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.RunAssetDiscoveryRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.run_asset_discovery, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Wrap the response in an operation future. + response = operation.from_gapic( + response, + self._transport.operations_client, + run_asset_discovery_response.RunAssetDiscoveryResponse, + metadata_type=empty.Empty, + ) + + # Done; return the response. + return response + + def set_finding_state( + self, + request: securitycenter_service.SetFindingStateRequest = None, + *, + name: str = None, + state: finding.Finding.State = None, + start_time: timestamp.Timestamp = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> finding.Finding: + r"""Updates the state of a finding. + + Args: + request (:class:`~.securitycenter_service.SetFindingStateRequest`): + The request object. Request message for updating a + finding's state. + name (:class:`str`): + Required. The relative resource name of the finding. + See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + This corresponds to the ``name`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + state (:class:`~.finding.Finding.State`): + Required. The desired State of the + finding. + This corresponds to the ``state`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + start_time (:class:`~.timestamp.Timestamp`): + Required. The time at which the + updated state takes effect. + This corresponds to the ``start_time`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.finding.Finding: + Security Command Center finding. + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([name, state, start_time]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.SetFindingStateRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if name is not None: + request.name = name + if state is not None: + request.state = state + if start_time is not None: + request.start_time = start_time + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_finding_state, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def set_iam_policy( + self, + request: iam_policy.SetIamPolicyRequest = None, + *, + resource: str = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> policy.Policy: + r"""Sets the access control policy on the specified + Source. + + Args: + request (:class:`~.iam_policy.SetIamPolicyRequest`): + The request object. Request message for `SetIamPolicy` + method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy is being specified. See the + operation documentation for the + appropriate value for this field. + This corresponds to the ``resource`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.policy.Policy: + Defines an Identity and Access Management (IAM) policy. + It is used to specify access control policies for Cloud + Platform resources. + + A ``Policy`` is a collection of ``bindings``. A + ``binding`` binds one or more ``members`` to a single + ``role``. Members can be user accounts, service + accounts, Google groups, and domains (such as G Suite). + A ``role`` is a named list of permissions (defined by + IAM or configured by users). A ``binding`` can + optionally specify a ``condition``, which is a logic + expression that further constrains the role binding + based on attributes about the request and/or target + resource. + + **JSON Example** + + :: + + { + "bindings": [ + { + "role": "roles/resourcemanager.organizationAdmin", + "members": [ + "user:mike@example.com", + "group:admins@example.com", + "domain:google.com", + "serviceAccount:my-project-id@appspot.gserviceaccount.com" + ] + }, + { + "role": "roles/resourcemanager.organizationViewer", + "members": ["user:eve@example.com"], + "condition": { + "title": "expirable access", + "description": "Does not grant access after Sep 2020", + "expression": "request.time < + timestamp('2020-10-01T00:00:00.000Z')", + } + } + ] + } + + **YAML Example** + + :: + + bindings: + - members: + - user:mike@example.com + - group:admins@example.com + - domain:google.com + - serviceAccount:my-project-id@appspot.gserviceaccount.com + role: roles/resourcemanager.organizationAdmin + - members: + - user:eve@example.com + role: roles/resourcemanager.organizationViewer + condition: + title: expirable access + description: Does not grant access after Sep 2020 + expression: request.time < timestamp('2020-10-01T00:00:00.000Z') + + For a description of IAM and its features, see the `IAM + developer's + guide `__. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([resource]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.SetIamPolicyRequest(**request) + + elif not request: + request = iam_policy.SetIamPolicyRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.resource = resource + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.set_iam_policy, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def test_iam_permissions( + self, + request: iam_policy.TestIamPermissionsRequest = None, + *, + resource: str = None, + permissions: Sequence[str] = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> iam_policy.TestIamPermissionsResponse: + r"""Returns the permissions that a caller has on the + specified source. + + Args: + request (:class:`~.iam_policy.TestIamPermissionsRequest`): + The request object. Request message for + `TestIamPermissions` method. + resource (:class:`str`): + REQUIRED: The resource for which the + policy detail is being requested. See + the operation documentation for the + appropriate value for this field. + This corresponds to the ``resource`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + permissions (:class:`Sequence[str]`): + The set of permissions to check for the ``resource``. + Permissions with wildcards (such as '*' or 'storage.*') + are not allowed. For more information see `IAM + Overview `__. + This corresponds to the ``permissions`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.iam_policy.TestIamPermissionsResponse: + Response message for ``TestIamPermissions`` method. + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([resource, permissions]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + # The request isn't a proto-plus wrapped type, + # so it must be constructed via keyword expansion. + if isinstance(request, dict): + request = iam_policy.TestIamPermissionsRequest(**request) + + elif not request: + request = iam_policy.TestIamPermissionsRequest() + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if resource is not None: + request.resource = resource + + if permissions: + request.permissions.extend(permissions) + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.test_iam_permissions, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_finding( + self, + request: securitycenter_service.UpdateFindingRequest = None, + *, + finding: gcs_finding.Finding = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_finding.Finding: + r"""Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Args: + request (:class:`~.securitycenter_service.UpdateFindingRequest`): + The request object. Request message for updating or + creating a finding. + finding (:class:`~.gcs_finding.Finding`): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the + name must be alphanumeric and less than or equal to 32 + characters and greater than 0 characters in length. + This corresponds to the ``finding`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + The FieldMask to use when updating the finding resource. + This field should not be specified when creating a + finding. + + When updating a finding, an empty mask is treated as + updating all mutable fields and replacing + source_properties. Individual source_properties can be + added/updated by using "source_properties." in the field + mask. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_finding.Finding: + Security Command Center finding. + A finding is a record of assessment data + (security, risk, health or privacy) + ingested into Security Command Center + for presentation, notification, + analysis, policy testing, and + enforcement. For example, an XSS + vulnerability in an App Engine + application is a finding. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([finding, update_mask]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.UpdateFindingRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if finding is not None: + request.finding = finding + 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 = gapic_v1.method.wrap_method( + self._transport.update_finding, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("finding.name", request.finding.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_notification_config( + self, + request: securitycenter_service.UpdateNotificationConfigRequest = None, + *, + notification_config: gcs_notification_config.NotificationConfig = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_notification_config.NotificationConfig: + r"""Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Args: + request (:class:`~.securitycenter_service.UpdateNotificationConfigRequest`): + The request object. Request message for updating a + notification config. + notification_config (:class:`~.gcs_notification_config.NotificationConfig`): + Required. The notification config to + update. + This corresponds to the ``notification_config`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + The FieldMask to use when updating + the notification config. + If empty all mutable fields will be + updated. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_notification_config.NotificationConfig: + Security Command Center notification + configs. + A notification config is a Security + Command Center resource that contains + the configuration to send notifications + for create/update events of findings, + assets and etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([notification_config, update_mask]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.UpdateNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if notification_config is not None: + request.notification_config = notification_config + 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 = gapic_v1.method.wrap_method( + self._transport.update_notification_config, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("notification_config.name", request.notification_config.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_organization_settings( + self, + request: securitycenter_service.UpdateOrganizationSettingsRequest = None, + *, + organization_settings: gcs_organization_settings.OrganizationSettings = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_organization_settings.OrganizationSettings: + r"""Updates an organization's settings. + + Args: + request (:class:`~.securitycenter_service.UpdateOrganizationSettingsRequest`): + The request object. Request message for updating an + organization's settings. + organization_settings (:class:`~.gcs_organization_settings.OrganizationSettings`): + Required. The organization settings + resource to update. + This corresponds to the ``organization_settings`` 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_organization_settings.OrganizationSettings: + User specified settings that are + attached to the Security Command Center + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([organization_settings]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.UpdateOrganizationSettingsRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if organization_settings is not None: + request.organization_settings = organization_settings + + # Wrap the RPC method; this adds retry and timeout information, + # and friendly error handling. + rpc = gapic_v1.method.wrap_method( + self._transport.update_organization_settings, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("organization_settings.name", request.organization_settings.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_source( + self, + request: securitycenter_service.UpdateSourceRequest = None, + *, + source: gcs_source.Source = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_source.Source: + r"""Updates a source. + + Args: + request (:class:`~.securitycenter_service.UpdateSourceRequest`): + The request object. Request message for updating a + source. + source (:class:`~.gcs_source.Source`): + Required. The source resource to + update. + This corresponds to the ``source`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + The FieldMask to use when updating + the source resource. + If empty all mutable fields will be + updated. + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_source.Source: + Security Command Center finding + source. A finding source is an entity or + a mechanism that can produce a finding. + A source is like a container of findings + that come from the same scanner, logger, + monitor, etc. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([source, update_mask]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.UpdateSourceRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if source is not None: + request.source = source + 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 = gapic_v1.method.wrap_method( + self._transport.update_source, + default_timeout=60.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("source.name", request.source.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + def update_security_marks( + self, + request: securitycenter_service.UpdateSecurityMarksRequest = None, + *, + security_marks: gcs_security_marks.SecurityMarks = None, + update_mask: field_mask.FieldMask = None, + retry: retries.Retry = gapic_v1.method.DEFAULT, + timeout: float = None, + metadata: Sequence[Tuple[str, str]] = (), + ) -> gcs_security_marks.SecurityMarks: + r"""Updates security marks. + + Args: + request (:class:`~.securitycenter_service.UpdateSecurityMarksRequest`): + The request object. Request message for updating a + SecurityMarks resource. + security_marks (:class:`~.gcs_security_marks.SecurityMarks`): + Required. The security marks resource + to update. + This corresponds to the ``security_marks`` field + on the ``request`` instance; if ``request`` is provided, this + should not be set. + update_mask (:class:`~.field_mask.FieldMask`): + The FieldMask to use when updating the security marks + resource. + + The field mask must not contain duplicate fields. If + empty or set to "marks", all marks will be replaced. + Individual marks can be updated using + "marks.". + 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, str]]): Strings which should be + sent along with the request as metadata. + + Returns: + ~.gcs_security_marks.SecurityMarks: + User specified security marks that + are attached to the parent Security + Command Center resource. Security marks + are scoped within a Security Command + Center organization -- they can be + modified and viewed by all users who + have proper permissions on the + organization. + + """ + # Create or coerce a protobuf request object. + # Sanity check: If we got a request object, we should *not* have + # gotten any keyword arguments that map to the request. + if request is not None and any([security_marks, update_mask]): + raise ValueError( + "If the `request` argument is set, then none of " + "the individual field arguments should be set." + ) + + request = securitycenter_service.UpdateSecurityMarksRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if security_marks is not None: + request.security_marks = security_marks + 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 = gapic_v1.method.wrap_method( + self._transport.update_security_marks, + default_timeout=480.0, + client_info=_client_info, + ) + + # Certain fields should be provided within the metadata header; + # add these here. + metadata = tuple(metadata) + ( + gapic_v1.routing_header.to_grpc_metadata( + (("security_marks.name", request.security_marks.name),) + ), + ) + + # Send the request. + response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) + + # Done; return the response. + return response + + +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-securitycenter", + ).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + +__all__ = ("SecurityCenterClient",) diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py new file mode 100644 index 00000000..561db76f --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py @@ -0,0 +1,804 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple + +from google.cloud.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source + + +class GroupAssetsPager: + """A pager for iterating through ``group_assets`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.GroupAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GroupAssets`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.GroupAssetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., securitycenter_service.GroupAssetsResponse], + request: securitycenter_service.GroupAssetsRequest, + response: securitycenter_service.GroupAssetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.GroupAssetsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.GroupAssetsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.GroupAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.GroupAssetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[securitycenter_service.GroupResult]: + for page in self.pages: + yield from page.group_by_results + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class GroupAssetsAsyncPager: + """A pager for iterating through ``group_assets`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.GroupAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GroupAssets`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.GroupAssetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[securitycenter_service.GroupAssetsResponse]], + request: securitycenter_service.GroupAssetsRequest, + response: securitycenter_service.GroupAssetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.GroupAssetsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.GroupAssetsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.GroupAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.GroupAssetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[securitycenter_service.GroupResult]: + async def async_generator(): + async for page in self.pages: + for response in page.group_by_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class GroupFindingsPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.GroupFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.GroupFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., securitycenter_service.GroupFindingsResponse], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.GroupFindingsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.GroupFindingsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.GroupFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.GroupFindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[securitycenter_service.GroupResult]: + for page in self.pages: + yield from page.group_by_results + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class GroupFindingsAsyncPager: + """A pager for iterating through ``group_findings`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.GroupFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``group_by_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``GroupFindings`` requests and continue to iterate + through the ``group_by_results`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.GroupFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[securitycenter_service.GroupFindingsResponse]], + request: securitycenter_service.GroupFindingsRequest, + response: securitycenter_service.GroupFindingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.GroupFindingsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.GroupFindingsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.GroupFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterable[securitycenter_service.GroupFindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[securitycenter_service.GroupResult]: + async def async_generator(): + async for page in self.pages: + for response in page.group_by_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAssetsPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.ListAssetsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``list_assets_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``list_assets_results`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.ListAssetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., securitycenter_service.ListAssetsResponse], + request: securitycenter_service.ListAssetsRequest, + response: securitycenter_service.ListAssetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListAssetsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.ListAssetsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.ListAssetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__( + self, + ) -> Iterable[securitycenter_service.ListAssetsResponse.ListAssetsResult]: + for page in self.pages: + yield from page.list_assets_results + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListAssetsAsyncPager: + """A pager for iterating through ``list_assets`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.ListAssetsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``list_assets_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListAssets`` requests and continue to iterate + through the ``list_assets_results`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.ListAssetsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[securitycenter_service.ListAssetsResponse]], + request: securitycenter_service.ListAssetsRequest, + response: securitycenter_service.ListAssetsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListAssetsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.ListAssetsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListAssetsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.ListAssetsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__( + self, + ) -> AsyncIterable[securitycenter_service.ListAssetsResponse.ListAssetsResult]: + async def async_generator(): + async for page in self.pages: + for response in page.list_assets_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListFindingsPager: + """A pager for iterating through ``list_findings`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.ListFindingsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``list_findings_results`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``list_findings_results`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.ListFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., securitycenter_service.ListFindingsResponse], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.ListFindingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListFindingsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.ListFindingsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.ListFindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__( + self, + ) -> Iterable[securitycenter_service.ListFindingsResponse.ListFindingsResult]: + for page in self.pages: + yield from page.list_findings_results + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListFindingsAsyncPager: + """A pager for iterating through ``list_findings`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.ListFindingsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``list_findings_results`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListFindings`` requests and continue to iterate + through the ``list_findings_results`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.ListFindingsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[securitycenter_service.ListFindingsResponse]], + request: securitycenter_service.ListFindingsRequest, + response: securitycenter_service.ListFindingsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListFindingsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.ListFindingsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListFindingsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.ListFindingsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__( + self, + ) -> AsyncIterable[securitycenter_service.ListFindingsResponse.ListFindingsResult]: + async def async_generator(): + async for page in self.pages: + for response in page.list_findings_results: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListNotificationConfigsPager: + """A pager for iterating through ``list_notification_configs`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.ListNotificationConfigsResponse` object, and + provides an ``__iter__`` method to iterate through its + ``notification_configs`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListNotificationConfigs`` requests and continue to iterate + through the ``notification_configs`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.ListNotificationConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., securitycenter_service.ListNotificationConfigsResponse], + request: securitycenter_service.ListNotificationConfigsRequest, + response: securitycenter_service.ListNotificationConfigsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListNotificationConfigsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.ListNotificationConfigsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListNotificationConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.ListNotificationConfigsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[notification_config.NotificationConfig]: + for page in self.pages: + yield from page.notification_configs + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListNotificationConfigsAsyncPager: + """A pager for iterating through ``list_notification_configs`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.ListNotificationConfigsResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``notification_configs`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListNotificationConfigs`` requests and continue to iterate + through the ``notification_configs`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.ListNotificationConfigsResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[ + ..., Awaitable[securitycenter_service.ListNotificationConfigsResponse] + ], + request: securitycenter_service.ListNotificationConfigsRequest, + response: securitycenter_service.ListNotificationConfigsResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListNotificationConfigsRequest`): + The initial request object. + response (:class:`~.securitycenter_service.ListNotificationConfigsResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListNotificationConfigsRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages( + self, + ) -> AsyncIterable[securitycenter_service.ListNotificationConfigsResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[notification_config.NotificationConfig]: + async def async_generator(): + async for page in self.pages: + for response in page.notification_configs: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSourcesPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.ListSourcesResponse` object, and + provides an ``__iter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__iter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.ListSourcesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., securitycenter_service.ListSourcesResponse], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListSourcesRequest`): + The initial request object. + response (:class:`~.securitycenter_service.ListSourcesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListSourcesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + def pages(self) -> Iterable[securitycenter_service.ListSourcesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = self._method(self._request, metadata=self._metadata) + yield self._response + + def __iter__(self) -> Iterable[source.Source]: + for page in self.pages: + yield from page.sources + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) + + +class ListSourcesAsyncPager: + """A pager for iterating through ``list_sources`` requests. + + This class thinly wraps an initial + :class:`~.securitycenter_service.ListSourcesResponse` object, and + provides an ``__aiter__`` method to iterate through its + ``sources`` field. + + If there are more pages, the ``__aiter__`` method will make additional + ``ListSources`` requests and continue to iterate + through the ``sources`` field on the + corresponding responses. + + All the usual :class:`~.securitycenter_service.ListSourcesResponse` + attributes are available on the pager. If multiple requests are made, only + the most recent response is retained, and thus used for attribute lookup. + """ + + def __init__( + self, + method: Callable[..., Awaitable[securitycenter_service.ListSourcesResponse]], + request: securitycenter_service.ListSourcesRequest, + response: securitycenter_service.ListSourcesResponse, + *, + metadata: Sequence[Tuple[str, str]] = () + ): + """Instantiate the pager. + + Args: + method (Callable): The method that was originally called, and + which instantiated this pager. + request (:class:`~.securitycenter_service.ListSourcesRequest`): + The initial request object. + response (:class:`~.securitycenter_service.ListSourcesResponse`): + The initial response object. + metadata (Sequence[Tuple[str, str]]): Strings which should be + sent along with the request as metadata. + """ + self._method = method + self._request = securitycenter_service.ListSourcesRequest(request) + self._response = response + self._metadata = metadata + + def __getattr__(self, name: str) -> Any: + return getattr(self._response, name) + + @property + async def pages(self) -> AsyncIterable[securitycenter_service.ListSourcesResponse]: + yield self._response + while self._response.next_page_token: + self._request.page_token = self._response.next_page_token + self._response = await self._method(self._request, metadata=self._metadata) + yield self._response + + def __aiter__(self) -> AsyncIterable[source.Source]: + async def async_generator(): + async for page in self.pages: + for response in page.sources: + yield response + + return async_generator() + + def __repr__(self) -> str: + return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py new file mode 100644 index 00000000..20423f2a --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py @@ -0,0 +1,36 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 typing import Dict, Type + +from .base import SecurityCenterTransport +from .grpc import SecurityCenterGrpcTransport +from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport + + +# Compile a registry of transports. +_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] +_transport_registry["grpc"] = SecurityCenterGrpcTransport +_transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport + + +__all__ = ( + "SecurityCenterTransport", + "SecurityCenterGrpcTransport", + "SecurityCenterGrpcAsyncIOTransport", +) diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py new file mode 100644 index 00000000..ddb8520d --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py @@ -0,0 +1,356 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 +import typing + +from google import auth +from google.api_core import exceptions # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials # type: ignore + +from google.cloud.securitycenter_v1p1beta1.types import finding +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import ( + notification_config as gcs_notification_config, +) +from google.cloud.securitycenter_v1p1beta1.types import organization_settings +from google.cloud.securitycenter_v1p1beta1.types import ( + organization_settings as gcs_organization_settings, +) +from google.cloud.securitycenter_v1p1beta1.types import ( + security_marks as gcs_security_marks, +) +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.longrunning import operations_pb2 as operations # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + + +class SecurityCenterTransport(abc.ABC): + """Abstract transport class for SecurityCenter.""" + + AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) + + def __init__( + self, + *, + host: str = "securitycenter.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: typing.Optional[str] = None, + scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, + quota_project_id: typing.Optional[str] = None, + **kwargs, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + 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]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scope (Optional[Sequence[str]]): A list of scopes. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + """ + # Save the hostname. Default to port 443 (HTTPS) if none is specified. + if ":" not in host: + host += ":443" + self._host = host + + # If no credentials are provided, then determine the appropriate + # defaults. + if credentials and credentials_file: + raise exceptions.DuplicateCredentialArgs( + "'credentials_file' and 'credentials' are mutually exclusive" + ) + + if credentials_file is not None: + credentials, _ = auth.load_credentials_from_file( + credentials_file, scopes=scopes, quota_project_id=quota_project_id + ) + + elif credentials is None: + credentials, _ = auth.default( + scopes=scopes, quota_project_id=quota_project_id + ) + + # Save the credentials. + self._credentials = credentials + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Return the client designed to process long-running operations.""" + raise NotImplementedError() + + @property + def create_source( + self, + ) -> typing.Callable[ + [securitycenter_service.CreateSourceRequest], + typing.Union[gcs_source.Source, typing.Awaitable[gcs_source.Source]], + ]: + raise NotImplementedError() + + @property + def create_finding( + self, + ) -> typing.Callable[ + [securitycenter_service.CreateFindingRequest], + typing.Union[gcs_finding.Finding, typing.Awaitable[gcs_finding.Finding]], + ]: + raise NotImplementedError() + + @property + def create_notification_config( + self, + ) -> typing.Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + typing.Union[ + gcs_notification_config.NotificationConfig, + typing.Awaitable[gcs_notification_config.NotificationConfig], + ], + ]: + raise NotImplementedError() + + @property + def delete_notification_config( + self, + ) -> typing.Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], + typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], + ]: + raise NotImplementedError() + + @property + def get_iam_policy( + self, + ) -> typing.Callable[ + [iam_policy.GetIamPolicyRequest], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ]: + raise NotImplementedError() + + @property + def get_notification_config( + self, + ) -> typing.Callable[ + [securitycenter_service.GetNotificationConfigRequest], + typing.Union[ + notification_config.NotificationConfig, + typing.Awaitable[notification_config.NotificationConfig], + ], + ]: + raise NotImplementedError() + + @property + def get_organization_settings( + self, + ) -> typing.Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + typing.Union[ + organization_settings.OrganizationSettings, + typing.Awaitable[organization_settings.OrganizationSettings], + ], + ]: + raise NotImplementedError() + + @property + def get_source( + self, + ) -> typing.Callable[ + [securitycenter_service.GetSourceRequest], + typing.Union[source.Source, typing.Awaitable[source.Source]], + ]: + raise NotImplementedError() + + @property + def group_assets( + self, + ) -> typing.Callable[ + [securitycenter_service.GroupAssetsRequest], + typing.Union[ + securitycenter_service.GroupAssetsResponse, + typing.Awaitable[securitycenter_service.GroupAssetsResponse], + ], + ]: + raise NotImplementedError() + + @property + def group_findings( + self, + ) -> typing.Callable[ + [securitycenter_service.GroupFindingsRequest], + typing.Union[ + securitycenter_service.GroupFindingsResponse, + typing.Awaitable[securitycenter_service.GroupFindingsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_assets( + self, + ) -> typing.Callable[ + [securitycenter_service.ListAssetsRequest], + typing.Union[ + securitycenter_service.ListAssetsResponse, + typing.Awaitable[securitycenter_service.ListAssetsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_findings( + self, + ) -> typing.Callable[ + [securitycenter_service.ListFindingsRequest], + typing.Union[ + securitycenter_service.ListFindingsResponse, + typing.Awaitable[securitycenter_service.ListFindingsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_notification_configs( + self, + ) -> typing.Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + typing.Union[ + securitycenter_service.ListNotificationConfigsResponse, + typing.Awaitable[securitycenter_service.ListNotificationConfigsResponse], + ], + ]: + raise NotImplementedError() + + @property + def list_sources( + self, + ) -> typing.Callable[ + [securitycenter_service.ListSourcesRequest], + typing.Union[ + securitycenter_service.ListSourcesResponse, + typing.Awaitable[securitycenter_service.ListSourcesResponse], + ], + ]: + raise NotImplementedError() + + @property + def run_asset_discovery( + self, + ) -> typing.Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], + ]: + raise NotImplementedError() + + @property + def set_finding_state( + self, + ) -> typing.Callable[ + [securitycenter_service.SetFindingStateRequest], + typing.Union[finding.Finding, typing.Awaitable[finding.Finding]], + ]: + raise NotImplementedError() + + @property + def set_iam_policy( + self, + ) -> typing.Callable[ + [iam_policy.SetIamPolicyRequest], + typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], + ]: + raise NotImplementedError() + + @property + def test_iam_permissions( + self, + ) -> typing.Callable[ + [iam_policy.TestIamPermissionsRequest], + typing.Union[ + iam_policy.TestIamPermissionsResponse, + typing.Awaitable[iam_policy.TestIamPermissionsResponse], + ], + ]: + raise NotImplementedError() + + @property + def update_finding( + self, + ) -> typing.Callable[ + [securitycenter_service.UpdateFindingRequest], + typing.Union[gcs_finding.Finding, typing.Awaitable[gcs_finding.Finding]], + ]: + raise NotImplementedError() + + @property + def update_notification_config( + self, + ) -> typing.Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + typing.Union[ + gcs_notification_config.NotificationConfig, + typing.Awaitable[gcs_notification_config.NotificationConfig], + ], + ]: + raise NotImplementedError() + + @property + def update_organization_settings( + self, + ) -> typing.Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + typing.Union[ + gcs_organization_settings.OrganizationSettings, + typing.Awaitable[gcs_organization_settings.OrganizationSettings], + ], + ]: + raise NotImplementedError() + + @property + def update_source( + self, + ) -> typing.Callable[ + [securitycenter_service.UpdateSourceRequest], + typing.Union[gcs_source.Source, typing.Awaitable[gcs_source.Source]], + ]: + raise NotImplementedError() + + @property + def update_security_marks( + self, + ) -> typing.Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + typing.Union[ + gcs_security_marks.SecurityMarks, + typing.Awaitable[gcs_security_marks.SecurityMarks], + ], + ]: + raise NotImplementedError() + + +__all__ = ("SecurityCenterTransport",) diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py new file mode 100644 index 00000000..e4d1f0e1 --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py @@ -0,0 +1,904 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 typing import Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers # type: ignore +from google.api_core import operations_v1 # type: ignore +from google import auth # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + + +import grpc # type: ignore + +from google.cloud.securitycenter_v1p1beta1.types import finding +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import ( + notification_config as gcs_notification_config, +) +from google.cloud.securitycenter_v1p1beta1.types import organization_settings +from google.cloud.securitycenter_v1p1beta1.types import ( + organization_settings as gcs_organization_settings, +) +from google.cloud.securitycenter_v1p1beta1.types import ( + security_marks as gcs_security_marks, +) +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.longrunning import operations_pb2 as operations # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import SecurityCenterTransport + + +class SecurityCenterGrpcTransport(SecurityCenterTransport): + """gRPC backend transport for SecurityCenter. + + V1p1Beta1 APIs for Security Center service. + + 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 = "securitycenter.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Sequence[str] = None, + channel: grpc.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id: Optional[str] = None + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + 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 ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional(Sequence[str])): A list of scopes. This argument is + ignored if ``channel`` is provided. + channel (Optional[grpc.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): 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 applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + 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. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + if credentials is None: + credentials, _ = auth.default( + scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} # type: Dict[str, Callable] + + @classmethod + def create_channel( + cls, + host: str = "securitycenter.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: str = None, + scopes: Optional[Sequence[str]] = None, + quota_project_id: Optional[str] = None, + **kwargs + ) -> grpc.Channel: + """Create and return a gRPC channel object. + Args: + address (Optionsl[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]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is mutually exclusive with credentials. + scopes (Optional[Sequence[str]]): A optional 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. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs + ) + + @property + def grpc_channel(self) -> grpc.Channel: + """Create the channel designed to connect to this service. + + This property caches on the instance; repeated calls return + the same channel. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def create_source( + self, + ) -> Callable[[securitycenter_service.CreateSourceRequest], gcs_source.Source]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + ~.Source]: + 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_source" not in self._stubs: + self._stubs["create_source"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateSource", + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs["create_source"] + + @property + def create_finding( + self, + ) -> Callable[[securitycenter_service.CreateFindingRequest], gcs_finding.Finding]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + ~.Finding]: + 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_finding" not in self._stubs: + self._stubs["create_finding"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateFinding", + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs["create_finding"] + + @property + def create_notification_config( + self, + ) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + gcs_notification_config.NotificationConfig, + ]: + r"""Return a callable for the create notification config method over gRPC. + + Creates a notification config. + + Returns: + Callable[[~.CreateNotificationConfigRequest], + ~.NotificationConfig]: + 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_notification_config" not in self._stubs: + self._stubs["create_notification_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateNotificationConfig", + request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs["create_notification_config"] + + @property + def delete_notification_config( + self, + ) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], empty.Empty + ]: + r"""Return a callable for the delete notification config method over gRPC. + + Deletes a notification config. + + Returns: + Callable[[~.DeleteNotificationConfigRequest], + ~.Empty]: + 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 "delete_notification_config" not in self._stubs: + self._stubs["delete_notification_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/DeleteNotificationConfig", + request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_notification_config"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy.GetIamPolicyRequest], policy.Policy]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the access control policy on the specified + Source. + + Returns: + Callable[[~.GetIamPolicyRequest], + ~.Policy]: + 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 "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetIamPolicy", + request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def get_notification_config( + self, + ) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + notification_config.NotificationConfig, + ]: + r"""Return a callable for the get notification config method over gRPC. + + Gets a notification config. + + Returns: + Callable[[~.GetNotificationConfigRequest], + ~.NotificationConfig]: + 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 "get_notification_config" not in self._stubs: + self._stubs["get_notification_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetNotificationConfig", + request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, + response_deserializer=notification_config.NotificationConfig.deserialize, + ) + return self._stubs["get_notification_config"] + + @property + def get_organization_settings( + self, + ) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + organization_settings.OrganizationSettings, + ]: + r"""Return a callable for the get organization settings method over gRPC. + + Gets the settings for an organization. + + Returns: + Callable[[~.GetOrganizationSettingsRequest], + ~.OrganizationSettings]: + 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 "get_organization_settings" not in self._stubs: + self._stubs["get_organization_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetOrganizationSettings", + request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, + response_deserializer=organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs["get_organization_settings"] + + @property + def get_source( + self, + ) -> Callable[[securitycenter_service.GetSourceRequest], source.Source]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + ~.Source]: + 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 "get_source" not in self._stubs: + self._stubs["get_source"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetSource", + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs["get_source"] + + @property + def group_assets( + self, + ) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + securitycenter_service.GroupAssetsResponse, + ]: + r"""Return a callable for the group assets method over gRPC. + + Filters an organization's assets and groups them by + their specified properties. + + Returns: + Callable[[~.GroupAssetsRequest], + ~.GroupAssetsResponse]: + 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 "group_assets" not in self._stubs: + self._stubs["group_assets"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupAssets", + request_serializer=securitycenter_service.GroupAssetsRequest.serialize, + response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, + ) + return self._stubs["group_assets"] + + @property + def group_findings( + self, + ) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + securitycenter_service.GroupFindingsResponse, + ]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: + /v1p1beta1/organizations/{organization_id}/sources/-/findings + + Returns: + Callable[[~.GroupFindingsRequest], + ~.GroupFindingsResponse]: + 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 "group_findings" not in self._stubs: + self._stubs["group_findings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupFindings", + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs["group_findings"] + + @property + def list_assets( + self, + ) -> Callable[ + [securitycenter_service.ListAssetsRequest], + securitycenter_service.ListAssetsResponse, + ]: + r"""Return a callable for the list assets method over gRPC. + + Lists an organization's assets. + + Returns: + Callable[[~.ListAssetsRequest], + ~.ListAssetsResponse]: + 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 "list_assets" not in self._stubs: + self._stubs["list_assets"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListAssets", + request_serializer=securitycenter_service.ListAssetsRequest.serialize, + response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, + ) + return self._stubs["list_assets"] + + @property + def list_findings( + self, + ) -> Callable[ + [securitycenter_service.ListFindingsRequest], + securitycenter_service.ListFindingsResponse, + ]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1p1beta1/organizations/{organization_id}/sources/-/findings + + Returns: + Callable[[~.ListFindingsRequest], + ~.ListFindingsResponse]: + 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 "list_findings" not in self._stubs: + self._stubs["list_findings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListFindings", + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs["list_findings"] + + @property + def list_notification_configs( + self, + ) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + securitycenter_service.ListNotificationConfigsResponse, + ]: + r"""Return a callable for the list notification configs method over gRPC. + + Lists notification configs. + + Returns: + Callable[[~.ListNotificationConfigsRequest], + ~.ListNotificationConfigsResponse]: + 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 "list_notification_configs" not in self._stubs: + self._stubs["list_notification_configs"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListNotificationConfigs", + request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, + ) + return self._stubs["list_notification_configs"] + + @property + def list_sources( + self, + ) -> Callable[ + [securitycenter_service.ListSourcesRequest], + securitycenter_service.ListSourcesResponse, + ]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + ~.ListSourcesResponse]: + 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 "list_sources" not in self._stubs: + self._stubs["list_sources"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListSources", + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs["list_sources"] + + @property + def run_asset_discovery( + self, + ) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], operations.Operation + ]: + r"""Return a callable for the run asset discovery method over gRPC. + + Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Returns: + Callable[[~.RunAssetDiscoveryRequest], + ~.Operation]: + 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 "run_asset_discovery" not in self._stubs: + self._stubs["run_asset_discovery"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/RunAssetDiscovery", + request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["run_asset_discovery"] + + @property + def set_finding_state( + self, + ) -> Callable[[securitycenter_service.SetFindingStateRequest], finding.Finding]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. + + Returns: + Callable[[~.SetFindingStateRequest], + ~.Finding]: + 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 "set_finding_state" not in self._stubs: + self._stubs["set_finding_state"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/SetFindingState", + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs["set_finding_state"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy.SetIamPolicyRequest], policy.Policy]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the access control policy on the specified + Source. + + Returns: + Callable[[~.SetIamPolicyRequest], + ~.Policy]: + 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 "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/SetIamPolicy", + request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy.TestIamPermissionsRequest], iam_policy.TestIamPermissionsResponse + ]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns the permissions that a caller has on the + specified source. + + Returns: + Callable[[~.TestIamPermissionsRequest], + ~.TestIamPermissionsResponse]: + 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 "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/TestIamPermissions", + request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def update_finding( + self, + ) -> Callable[[securitycenter_service.UpdateFindingRequest], gcs_finding.Finding]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + ~.Finding]: + 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_finding" not in self._stubs: + self._stubs["update_finding"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateFinding", + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs["update_finding"] + + @property + def update_notification_config( + self, + ) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + gcs_notification_config.NotificationConfig, + ]: + r"""Return a callable for the update notification config method over gRPC. + + Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Returns: + Callable[[~.UpdateNotificationConfigRequest], + ~.NotificationConfig]: + 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_notification_config" not in self._stubs: + self._stubs["update_notification_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateNotificationConfig", + request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs["update_notification_config"] + + @property + def update_organization_settings( + self, + ) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + gcs_organization_settings.OrganizationSettings, + ]: + r"""Return a callable for the update organization settings method over gRPC. + + Updates an organization's settings. + + Returns: + Callable[[~.UpdateOrganizationSettingsRequest], + ~.OrganizationSettings]: + 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_organization_settings" not in self._stubs: + self._stubs["update_organization_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateOrganizationSettings", + request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, + response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs["update_organization_settings"] + + @property + def update_source( + self, + ) -> Callable[[securitycenter_service.UpdateSourceRequest], gcs_source.Source]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + ~.Source]: + 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_source" not in self._stubs: + self._stubs["update_source"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSource", + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs["update_source"] + + @property + def update_security_marks( + self, + ) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + gcs_security_marks.SecurityMarks, + ]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + ~.SecurityMarks]: + 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_security_marks" not in self._stubs: + self._stubs["update_security_marks"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSecurityMarks", + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs["update_security_marks"] + + +__all__ = ("SecurityCenterGrpcTransport",) diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py new file mode 100644 index 00000000..4fcf66ec --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py @@ -0,0 +1,909 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple + +from google.api_core import grpc_helpers_async # type: ignore +from google.api_core import operations_v1 # type: ignore +from google.auth import credentials # type: ignore +from google.auth.transport.grpc import SslCredentials # type: ignore + +import grpc # type: ignore +from grpc.experimental import aio # type: ignore + +from google.cloud.securitycenter_v1p1beta1.types import finding +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import notification_config +from google.cloud.securitycenter_v1p1beta1.types import ( + notification_config as gcs_notification_config, +) +from google.cloud.securitycenter_v1p1beta1.types import organization_settings +from google.cloud.securitycenter_v1p1beta1.types import ( + organization_settings as gcs_organization_settings, +) +from google.cloud.securitycenter_v1p1beta1.types import ( + security_marks as gcs_security_marks, +) +from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service +from google.cloud.securitycenter_v1p1beta1.types import source +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore +from google.iam.v1 import policy_pb2 as policy # type: ignore +from google.longrunning import operations_pb2 as operations # type: ignore +from google.protobuf import empty_pb2 as empty # type: ignore + +from .base import SecurityCenterTransport +from .grpc import SecurityCenterGrpcTransport + + +class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): + """gRPC AsyncIO backend transport for SecurityCenter. + + V1p1Beta1 APIs for Security Center service. + + 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 = "securitycenter.googleapis.com", + credentials: 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: + address (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]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional 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. + """ + scopes = scopes or cls.AUTH_SCOPES + return grpc_helpers_async.create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes, + quota_project_id=quota_project_id, + **kwargs, + ) + + def __init__( + self, + *, + host: str = "securitycenter.googleapis.com", + credentials: credentials.Credentials = None, + credentials_file: Optional[str] = None, + scopes: Optional[Sequence[str]] = None, + channel: aio.Channel = None, + api_mtls_endpoint: str = None, + client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, + quota_project_id=None, + ) -> None: + """Instantiate the transport. + + Args: + host (Optional[str]): The hostname to connect to. + 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 ``channel`` is provided. + credentials_file (Optional[str]): A file with credentials that can + be loaded with :func:`google.auth.load_credentials_from_file`. + This argument is ignored if ``channel`` is provided. + scopes (Optional[Sequence[str]]): A optional 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[aio.Channel]): A ``Channel`` instance through + which to make calls. + api_mtls_endpoint (Optional[str]): 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 applicatin default SSL credentials. + client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 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. + quota_project_id (Optional[str]): An optional project to use for billing + and quota. + + 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. + """ + if channel: + # Sanity check: Ensure that channel and credentials are not both + # provided. + credentials = False + + # If a channel was explicitly provided, set it. + self._grpc_channel = channel + elif api_mtls_endpoint: + host = ( + api_mtls_endpoint + if ":" in api_mtls_endpoint + else api_mtls_endpoint + ":443" + ) + + # Create SSL credentials with client_cert_source or application + # default SSL credentials. + if client_cert_source: + cert, key = client_cert_source() + ssl_credentials = grpc.ssl_channel_credentials( + certificate_chain=cert, private_key=key + ) + else: + ssl_credentials = SslCredentials().ssl_credentials + + # create a new channel. The provided one is ignored. + self._grpc_channel = type(self).create_channel( + host, + credentials=credentials, + credentials_file=credentials_file, + ssl_credentials=ssl_credentials, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + # Run the base constructor. + super().__init__( + host=host, + credentials=credentials, + credentials_file=credentials_file, + scopes=scopes or self.AUTH_SCOPES, + quota_project_id=quota_project_id, + ) + + self._stubs = {} + + @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. + """ + # Sanity check: Only create a new channel if we do not already + # have one. + if not hasattr(self, "_grpc_channel"): + self._grpc_channel = self.create_channel( + self._host, credentials=self._credentials, + ) + + # Return the channel from cache. + return self._grpc_channel + + @property + def operations_client(self) -> operations_v1.OperationsAsyncClient: + """Create the client designed to process long-running operations. + + This property caches on the instance; repeated calls return the same + client. + """ + # Sanity check: Only create a new client if we do not already have one. + if "operations_client" not in self.__dict__: + self.__dict__["operations_client"] = operations_v1.OperationsAsyncClient( + self.grpc_channel + ) + + # Return the client from cache. + return self.__dict__["operations_client"] + + @property + def create_source( + self, + ) -> Callable[ + [securitycenter_service.CreateSourceRequest], Awaitable[gcs_source.Source] + ]: + r"""Return a callable for the create source method over gRPC. + + Creates a source. + + Returns: + Callable[[~.CreateSourceRequest], + Awaitable[~.Source]]: + 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_source" not in self._stubs: + self._stubs["create_source"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateSource", + request_serializer=securitycenter_service.CreateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs["create_source"] + + @property + def create_finding( + self, + ) -> Callable[ + [securitycenter_service.CreateFindingRequest], Awaitable[gcs_finding.Finding] + ]: + r"""Return a callable for the create finding method over gRPC. + + Creates a finding. The corresponding source must + exist for finding creation to succeed. + + Returns: + Callable[[~.CreateFindingRequest], + Awaitable[~.Finding]]: + 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_finding" not in self._stubs: + self._stubs["create_finding"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateFinding", + request_serializer=securitycenter_service.CreateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs["create_finding"] + + @property + def create_notification_config( + self, + ) -> Callable[ + [securitycenter_service.CreateNotificationConfigRequest], + Awaitable[gcs_notification_config.NotificationConfig], + ]: + r"""Return a callable for the create notification config method over gRPC. + + Creates a notification config. + + Returns: + Callable[[~.CreateNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + 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_notification_config" not in self._stubs: + self._stubs["create_notification_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateNotificationConfig", + request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs["create_notification_config"] + + @property + def delete_notification_config( + self, + ) -> Callable[ + [securitycenter_service.DeleteNotificationConfigRequest], Awaitable[empty.Empty] + ]: + r"""Return a callable for the delete notification config method over gRPC. + + Deletes a notification config. + + Returns: + Callable[[~.DeleteNotificationConfigRequest], + Awaitable[~.Empty]]: + 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 "delete_notification_config" not in self._stubs: + self._stubs["delete_notification_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/DeleteNotificationConfig", + request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, + response_deserializer=empty.Empty.FromString, + ) + return self._stubs["delete_notification_config"] + + @property + def get_iam_policy( + self, + ) -> Callable[[iam_policy.GetIamPolicyRequest], Awaitable[policy.Policy]]: + r"""Return a callable for the get iam policy method over gRPC. + + Gets the access control policy on the specified + Source. + + Returns: + Callable[[~.GetIamPolicyRequest], + Awaitable[~.Policy]]: + 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 "get_iam_policy" not in self._stubs: + self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetIamPolicy", + request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["get_iam_policy"] + + @property + def get_notification_config( + self, + ) -> Callable[ + [securitycenter_service.GetNotificationConfigRequest], + Awaitable[notification_config.NotificationConfig], + ]: + r"""Return a callable for the get notification config method over gRPC. + + Gets a notification config. + + Returns: + Callable[[~.GetNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + 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 "get_notification_config" not in self._stubs: + self._stubs["get_notification_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetNotificationConfig", + request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, + response_deserializer=notification_config.NotificationConfig.deserialize, + ) + return self._stubs["get_notification_config"] + + @property + def get_organization_settings( + self, + ) -> Callable[ + [securitycenter_service.GetOrganizationSettingsRequest], + Awaitable[organization_settings.OrganizationSettings], + ]: + r"""Return a callable for the get organization settings method over gRPC. + + Gets the settings for an organization. + + Returns: + Callable[[~.GetOrganizationSettingsRequest], + Awaitable[~.OrganizationSettings]]: + 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 "get_organization_settings" not in self._stubs: + self._stubs["get_organization_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetOrganizationSettings", + request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, + response_deserializer=organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs["get_organization_settings"] + + @property + def get_source( + self, + ) -> Callable[[securitycenter_service.GetSourceRequest], Awaitable[source.Source]]: + r"""Return a callable for the get source method over gRPC. + + Gets a source. + + Returns: + Callable[[~.GetSourceRequest], + Awaitable[~.Source]]: + 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 "get_source" not in self._stubs: + self._stubs["get_source"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetSource", + request_serializer=securitycenter_service.GetSourceRequest.serialize, + response_deserializer=source.Source.deserialize, + ) + return self._stubs["get_source"] + + @property + def group_assets( + self, + ) -> Callable[ + [securitycenter_service.GroupAssetsRequest], + Awaitable[securitycenter_service.GroupAssetsResponse], + ]: + r"""Return a callable for the group assets method over gRPC. + + Filters an organization's assets and groups them by + their specified properties. + + Returns: + Callable[[~.GroupAssetsRequest], + Awaitable[~.GroupAssetsResponse]]: + 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 "group_assets" not in self._stubs: + self._stubs["group_assets"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupAssets", + request_serializer=securitycenter_service.GroupAssetsRequest.serialize, + response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, + ) + return self._stubs["group_assets"] + + @property + def group_findings( + self, + ) -> Callable[ + [securitycenter_service.GroupFindingsRequest], + Awaitable[securitycenter_service.GroupFindingsResponse], + ]: + r"""Return a callable for the group findings method over gRPC. + + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. + Example: + /v1p1beta1/organizations/{organization_id}/sources/-/findings + + Returns: + Callable[[~.GroupFindingsRequest], + Awaitable[~.GroupFindingsResponse]]: + 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 "group_findings" not in self._stubs: + self._stubs["group_findings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupFindings", + request_serializer=securitycenter_service.GroupFindingsRequest.serialize, + response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, + ) + return self._stubs["group_findings"] + + @property + def list_assets( + self, + ) -> Callable[ + [securitycenter_service.ListAssetsRequest], + Awaitable[securitycenter_service.ListAssetsResponse], + ]: + r"""Return a callable for the list assets method over gRPC. + + Lists an organization's assets. + + Returns: + Callable[[~.ListAssetsRequest], + Awaitable[~.ListAssetsResponse]]: + 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 "list_assets" not in self._stubs: + self._stubs["list_assets"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListAssets", + request_serializer=securitycenter_service.ListAssetsRequest.serialize, + response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, + ) + return self._stubs["list_assets"] + + @property + def list_findings( + self, + ) -> Callable[ + [securitycenter_service.ListFindingsRequest], + Awaitable[securitycenter_service.ListFindingsResponse], + ]: + r"""Return a callable for the list findings method over gRPC. + + Lists an organization or source's findings. + + To list across all sources provide a ``-`` as the source id. + Example: + /v1p1beta1/organizations/{organization_id}/sources/-/findings + + Returns: + Callable[[~.ListFindingsRequest], + Awaitable[~.ListFindingsResponse]]: + 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 "list_findings" not in self._stubs: + self._stubs["list_findings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListFindings", + request_serializer=securitycenter_service.ListFindingsRequest.serialize, + response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, + ) + return self._stubs["list_findings"] + + @property + def list_notification_configs( + self, + ) -> Callable[ + [securitycenter_service.ListNotificationConfigsRequest], + Awaitable[securitycenter_service.ListNotificationConfigsResponse], + ]: + r"""Return a callable for the list notification configs method over gRPC. + + Lists notification configs. + + Returns: + Callable[[~.ListNotificationConfigsRequest], + Awaitable[~.ListNotificationConfigsResponse]]: + 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 "list_notification_configs" not in self._stubs: + self._stubs["list_notification_configs"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListNotificationConfigs", + request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, + response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, + ) + return self._stubs["list_notification_configs"] + + @property + def list_sources( + self, + ) -> Callable[ + [securitycenter_service.ListSourcesRequest], + Awaitable[securitycenter_service.ListSourcesResponse], + ]: + r"""Return a callable for the list sources method over gRPC. + + Lists all sources belonging to an organization. + + Returns: + Callable[[~.ListSourcesRequest], + Awaitable[~.ListSourcesResponse]]: + 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 "list_sources" not in self._stubs: + self._stubs["list_sources"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListSources", + request_serializer=securitycenter_service.ListSourcesRequest.serialize, + response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, + ) + return self._stubs["list_sources"] + + @property + def run_asset_discovery( + self, + ) -> Callable[ + [securitycenter_service.RunAssetDiscoveryRequest], + Awaitable[operations.Operation], + ]: + r"""Return a callable for the run asset discovery method over gRPC. + + Runs asset discovery. The discovery is tracked with a + long-running operation. + + This API can only be called with limited frequency for an + organization. If it is called too frequently the caller will + receive a TOO_MANY_REQUESTS error. + + Returns: + Callable[[~.RunAssetDiscoveryRequest], + Awaitable[~.Operation]]: + 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 "run_asset_discovery" not in self._stubs: + self._stubs["run_asset_discovery"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/RunAssetDiscovery", + request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, + response_deserializer=operations.Operation.FromString, + ) + return self._stubs["run_asset_discovery"] + + @property + def set_finding_state( + self, + ) -> Callable[ + [securitycenter_service.SetFindingStateRequest], Awaitable[finding.Finding] + ]: + r"""Return a callable for the set finding state method over gRPC. + + Updates the state of a finding. + + Returns: + Callable[[~.SetFindingStateRequest], + Awaitable[~.Finding]]: + 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 "set_finding_state" not in self._stubs: + self._stubs["set_finding_state"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/SetFindingState", + request_serializer=securitycenter_service.SetFindingStateRequest.serialize, + response_deserializer=finding.Finding.deserialize, + ) + return self._stubs["set_finding_state"] + + @property + def set_iam_policy( + self, + ) -> Callable[[iam_policy.SetIamPolicyRequest], Awaitable[policy.Policy]]: + r"""Return a callable for the set iam policy method over gRPC. + + Sets the access control policy on the specified + Source. + + Returns: + Callable[[~.SetIamPolicyRequest], + Awaitable[~.Policy]]: + 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 "set_iam_policy" not in self._stubs: + self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/SetIamPolicy", + request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, + response_deserializer=policy.Policy.FromString, + ) + return self._stubs["set_iam_policy"] + + @property + def test_iam_permissions( + self, + ) -> Callable[ + [iam_policy.TestIamPermissionsRequest], + Awaitable[iam_policy.TestIamPermissionsResponse], + ]: + r"""Return a callable for the test iam permissions method over gRPC. + + Returns the permissions that a caller has on the + specified source. + + Returns: + Callable[[~.TestIamPermissionsRequest], + Awaitable[~.TestIamPermissionsResponse]]: + 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 "test_iam_permissions" not in self._stubs: + self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/TestIamPermissions", + request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, + response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, + ) + return self._stubs["test_iam_permissions"] + + @property + def update_finding( + self, + ) -> Callable[ + [securitycenter_service.UpdateFindingRequest], Awaitable[gcs_finding.Finding] + ]: + r"""Return a callable for the update finding method over gRPC. + + Creates or updates a finding. The corresponding + source must exist for a finding creation to succeed. + + Returns: + Callable[[~.UpdateFindingRequest], + Awaitable[~.Finding]]: + 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_finding" not in self._stubs: + self._stubs["update_finding"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateFinding", + request_serializer=securitycenter_service.UpdateFindingRequest.serialize, + response_deserializer=gcs_finding.Finding.deserialize, + ) + return self._stubs["update_finding"] + + @property + def update_notification_config( + self, + ) -> Callable[ + [securitycenter_service.UpdateNotificationConfigRequest], + Awaitable[gcs_notification_config.NotificationConfig], + ]: + r"""Return a callable for the update notification config method over gRPC. + + Updates a notification config. The following update fields are + allowed: description, pubsub_topic, streaming_config.filter + + Returns: + Callable[[~.UpdateNotificationConfigRequest], + Awaitable[~.NotificationConfig]]: + 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_notification_config" not in self._stubs: + self._stubs["update_notification_config"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateNotificationConfig", + request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, + response_deserializer=gcs_notification_config.NotificationConfig.deserialize, + ) + return self._stubs["update_notification_config"] + + @property + def update_organization_settings( + self, + ) -> Callable[ + [securitycenter_service.UpdateOrganizationSettingsRequest], + Awaitable[gcs_organization_settings.OrganizationSettings], + ]: + r"""Return a callable for the update organization settings method over gRPC. + + Updates an organization's settings. + + Returns: + Callable[[~.UpdateOrganizationSettingsRequest], + Awaitable[~.OrganizationSettings]]: + 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_organization_settings" not in self._stubs: + self._stubs["update_organization_settings"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateOrganizationSettings", + request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, + response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, + ) + return self._stubs["update_organization_settings"] + + @property + def update_source( + self, + ) -> Callable[ + [securitycenter_service.UpdateSourceRequest], Awaitable[gcs_source.Source] + ]: + r"""Return a callable for the update source method over gRPC. + + Updates a source. + + Returns: + Callable[[~.UpdateSourceRequest], + Awaitable[~.Source]]: + 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_source" not in self._stubs: + self._stubs["update_source"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSource", + request_serializer=securitycenter_service.UpdateSourceRequest.serialize, + response_deserializer=gcs_source.Source.deserialize, + ) + return self._stubs["update_source"] + + @property + def update_security_marks( + self, + ) -> Callable[ + [securitycenter_service.UpdateSecurityMarksRequest], + Awaitable[gcs_security_marks.SecurityMarks], + ]: + r"""Return a callable for the update security marks method over gRPC. + + Updates security marks. + + Returns: + Callable[[~.UpdateSecurityMarksRequest], + Awaitable[~.SecurityMarks]]: + 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_security_marks" not in self._stubs: + self._stubs["update_security_marks"] = self.grpc_channel.unary_unary( + "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSecurityMarks", + request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, + response_deserializer=gcs_security_marks.SecurityMarks.deserialize, + ) + return self._stubs["update_security_marks"] + + +__all__ = ("SecurityCenterGrpcAsyncIOTransport",) diff --git a/google/cloud/securitycenter_v1p1beta1/types/__init__.py b/google/cloud/securitycenter_v1p1beta1/types/__init__.py new file mode 100644 index 00000000..c65c45b8 --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/types/__init__.py @@ -0,0 +1,95 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 .security_marks import SecurityMarks +from .asset import Asset +from .finding import Finding +from .notification_config import NotificationConfig +from .resource import Resource +from .notification_message import NotificationMessage +from .organization_settings import OrganizationSettings +from .run_asset_discovery_response import RunAssetDiscoveryResponse +from .source import Source +from .securitycenter_service import ( + CreateFindingRequest, + CreateNotificationConfigRequest, + CreateSourceRequest, + DeleteNotificationConfigRequest, + GetNotificationConfigRequest, + GetOrganizationSettingsRequest, + GetSourceRequest, + GroupAssetsRequest, + GroupAssetsResponse, + GroupFindingsRequest, + GroupFindingsResponse, + GroupResult, + ListNotificationConfigsRequest, + ListNotificationConfigsResponse, + ListSourcesRequest, + ListSourcesResponse, + ListAssetsRequest, + ListAssetsResponse, + ListFindingsRequest, + ListFindingsResponse, + SetFindingStateRequest, + RunAssetDiscoveryRequest, + UpdateFindingRequest, + UpdateNotificationConfigRequest, + UpdateOrganizationSettingsRequest, + UpdateSourceRequest, + UpdateSecurityMarksRequest, +) + + +__all__ = ( + "SecurityMarks", + "Asset", + "Finding", + "NotificationConfig", + "Resource", + "NotificationMessage", + "OrganizationSettings", + "RunAssetDiscoveryResponse", + "Source", + "CreateFindingRequest", + "CreateNotificationConfigRequest", + "CreateSourceRequest", + "DeleteNotificationConfigRequest", + "GetNotificationConfigRequest", + "GetOrganizationSettingsRequest", + "GetSourceRequest", + "GroupAssetsRequest", + "GroupAssetsResponse", + "GroupFindingsRequest", + "GroupFindingsResponse", + "GroupResult", + "ListNotificationConfigsRequest", + "ListNotificationConfigsResponse", + "ListSourcesRequest", + "ListSourcesResponse", + "ListAssetsRequest", + "ListAssetsResponse", + "ListFindingsRequest", + "ListFindingsResponse", + "SetFindingStateRequest", + "RunAssetDiscoveryRequest", + "UpdateFindingRequest", + "UpdateNotificationConfigRequest", + "UpdateOrganizationSettingsRequest", + "UpdateSourceRequest", + "UpdateSecurityMarksRequest", +) diff --git a/google/cloud/securitycenter_v1p1beta1/types/asset.py b/google/cloud/securitycenter_v1p1beta1/types/asset.py new file mode 100644 index 00000000..9d7f0742 --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/types/asset.py @@ -0,0 +1,168 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +from google.cloud.securitycenter_v1p1beta1.types import ( + security_marks as gcs_security_marks, +) +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1p1beta1", manifest={"Asset",}, +) + + +class Asset(proto.Message): + r"""Security Command Center representation of a Google Cloud + resource. + + The Asset is a Security Command Center resource that captures + information about a single Google Cloud resource. All + modifications to an Asset are only within the context of + Security Command Center and don't affect the referenced Google + Cloud resource. + + Attributes: + name (str): + The relative resource name of this asset. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/assets/{asset_id}". + security_center_properties (~.asset.Asset.SecurityCenterProperties): + Security Command Center managed properties. + These properties are managed by Security Command + Center and cannot be modified by the user. + resource_properties (Sequence[~.asset.Asset.ResourcePropertiesEntry]): + Resource managed properties. These properties + are managed and defined by the Google Cloud + resource and cannot be modified by the user. + security_marks (~.gcs_security_marks.SecurityMarks): + User specified security marks. These marks + are entirely managed by the user and come from + the SecurityMarks resource that belongs to the + asset. + create_time (~.timestamp.Timestamp): + The time at which the asset was created in + Security Command Center. + update_time (~.timestamp.Timestamp): + The time at which the asset was last updated, + added, or deleted in Cloud SCC. + iam_policy (~.asset.Asset.IamPolicy): + Cloud IAM Policy information associated with + the Google Cloud resource described by the + Security Command Center asset. This information + is managed and defined by the Google Cloud + resource and cannot be modified by the user. + """ + + class SecurityCenterProperties(proto.Message): + r"""Security Command Center managed properties. These properties + are managed by Security Command Center and cannot be modified by + the user. + + Attributes: + resource_name (str): + The full resource name of the Google Cloud resource this + asset represents. This field is immutable after create time. + See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_type (str): + The type of the Google Cloud resource. + Examples include: APPLICATION, PROJECT, and + ORGANIZATION. This is a case insensitive field + defined by Security Command Center and/or the + producer of the resource and is immutable after + create time. + resource_parent (str): + The full resource name of the immediate parent of the + resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_project (str): + The full resource name of the project the resource belongs + to. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + resource_owners (Sequence[str]): + Owners of the Google Cloud resource. + resource_display_name (str): + The user defined display name for this + resource. + resource_parent_display_name (str): + The user defined display name for the parent + of this resource. + resource_project_display_name (str): + The user defined display name for the project + of this resource. + """ + + resource_name = proto.Field(proto.STRING, number=1) + + resource_type = proto.Field(proto.STRING, number=2) + + resource_parent = proto.Field(proto.STRING, number=3) + + resource_project = proto.Field(proto.STRING, number=4) + + resource_owners = proto.RepeatedField(proto.STRING, number=5) + + resource_display_name = proto.Field(proto.STRING, number=6) + + resource_parent_display_name = proto.Field(proto.STRING, number=7) + + resource_project_display_name = proto.Field(proto.STRING, number=8) + + class IamPolicy(proto.Message): + r"""Cloud IAM Policy information associated with the Google Cloud + resource described by the Security Command Center asset. This + information is managed and defined by the Google Cloud resource + and cannot be modified by the user. + + Attributes: + policy_blob (str): + The JSON representation of the Policy + associated with the asset. See + https://cloud.google.com/iam/docs/reference/rest/v1/Policy + for format details. + """ + + policy_blob = proto.Field(proto.STRING, number=1) + + name = proto.Field(proto.STRING, number=1) + + security_center_properties = proto.Field( + proto.MESSAGE, number=2, message=SecurityCenterProperties, + ) + + resource_properties = proto.MapField( + proto.STRING, proto.MESSAGE, number=7, message=struct.Value, + ) + + security_marks = proto.Field( + proto.MESSAGE, number=8, message=gcs_security_marks.SecurityMarks, + ) + + create_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) + + update_time = proto.Field(proto.MESSAGE, number=10, message=timestamp.Timestamp,) + + iam_policy = proto.Field(proto.MESSAGE, number=11, message=IamPolicy,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/finding.py b/google/cloud/securitycenter_v1p1beta1/types/finding.py new file mode 100644 index 00000000..971aa3b4 --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/types/finding.py @@ -0,0 +1,125 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +from google.cloud.securitycenter_v1p1beta1.types import ( + security_marks as gcs_security_marks, +) +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1p1beta1", manifest={"Finding",}, +) + + +class Finding(proto.Message): + r"""Security Command Center finding. + A finding is a record of assessment data (security, risk, health + or privacy) ingested into Security Command Center for + presentation, notification, analysis, policy testing, and + enforcement. For example, an XSS vulnerability in an App Engine + application is a finding. + + Attributes: + name (str): + The relative resource name of this finding. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}". + parent (str): + The relative resource name of the source the finding belongs + to. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + This field is immutable after creation time. For example: + "organizations/{organization_id}/sources/{source_id}". + resource_name (str): + For findings on Google Cloud resources, the full resource + name of the Google Cloud resource this finding is for. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + When the finding is for a non-Google Cloud resource, the + resourceName can be a customer or partner defined string. + This field is immutable after creation time. + state (~.finding.Finding.State): + The state of the finding. + category (str): + The additional taxonomy group within findings from a given + source. This field is immutable after creation time. + Example: "XSS_FLASH_INJECTION". + external_uri (str): + The URI that, if available, points to a web + page outside of Security Command Center where + additional information about the finding can be + found. This field is guaranteed to be either + empty or a well formed URL. + source_properties (Sequence[~.finding.Finding.SourcePropertiesEntry]): + Source specific properties. These properties are managed by + the source that writes the finding. The key names in the + source_properties map must be between 1 and 255 characters, + and must start with a letter and contain alphanumeric + characters or underscores only. + security_marks (~.gcs_security_marks.SecurityMarks): + Output only. User specified security marks. + These marks are entirely managed by the user and + come from the SecurityMarks resource that + belongs to the finding. + event_time (~.timestamp.Timestamp): + The time at which the event took place. For + example, if the finding represents an open + firewall it would capture the time the detector + believes the firewall became open. The accuracy + is determined by the detector. + create_time (~.timestamp.Timestamp): + The time at which the finding was created in + Security Command Center. + """ + + class State(proto.Enum): + r"""The state of the finding.""" + STATE_UNSPECIFIED = 0 + ACTIVE = 1 + INACTIVE = 2 + + name = proto.Field(proto.STRING, number=1) + + parent = proto.Field(proto.STRING, number=2) + + resource_name = proto.Field(proto.STRING, number=3) + + state = proto.Field(proto.ENUM, number=4, enum=State,) + + category = proto.Field(proto.STRING, number=5) + + external_uri = proto.Field(proto.STRING, number=6) + + source_properties = proto.MapField( + proto.STRING, proto.MESSAGE, number=7, message=struct.Value, + ) + + security_marks = proto.Field( + proto.MESSAGE, number=8, message=gcs_security_marks.SecurityMarks, + ) + + event_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) + + create_time = proto.Field(proto.MESSAGE, number=10, message=timestamp.Timestamp,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/notification_config.py b/google/cloud/securitycenter_v1p1beta1/types/notification_config.py new file mode 100644 index 00000000..2be493b4 --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/types/notification_config.py @@ -0,0 +1,109 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1p1beta1", manifest={"NotificationConfig",}, +) + + +class NotificationConfig(proto.Message): + r"""Security Command Center notification configs. + A notification config is a Security Command Center resource that + contains the configuration to send notifications for + create/update events of findings, assets and etc. + + Attributes: + name (str): + The relative resource name of this notification config. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/notificationConfigs/notify_public_bucket". + description (str): + The description of the notification config + (max of 1024 characters). + event_type (~.notification_config.NotificationConfig.EventType): + The type of events the config is for, e.g. + FINDING. + pubsub_topic (str): + The Pub/Sub topic to send notifications to. Its format is + "projects/[project_id]/topics/[topic]". + service_account (str): + Output only. The service account that needs + "pubsub.topics.publish" permission to publish to + the Pub/Sub topic. + streaming_config (~.notification_config.NotificationConfig.StreamingConfig): + The config for triggering streaming-based + notifications. + """ + + class EventType(proto.Enum): + r"""The type of events.""" + EVENT_TYPE_UNSPECIFIED = 0 + FINDING = 1 + + class StreamingConfig(proto.Message): + r"""The config for streaming-based notifications, which send each + event as soon as it is detected. + + Attributes: + filter (str): + Expression that defines the filter to apply across + create/update events of assets or findings as specified by + the event type. The expression is a list of zero or more + restrictions combined via logical operators ``AND`` and + ``OR``. Parentheses are supported, and ``OR`` has higher + precedence than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the + corresponding resource. + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + """ + + filter = proto.Field(proto.STRING, number=1) + + name = proto.Field(proto.STRING, number=1) + + description = proto.Field(proto.STRING, number=2) + + event_type = proto.Field(proto.ENUM, number=3, enum=EventType,) + + pubsub_topic = proto.Field(proto.STRING, number=4) + + service_account = proto.Field(proto.STRING, number=5) + + streaming_config = proto.Field( + proto.MESSAGE, number=6, oneof="notify_config", message=StreamingConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/notification_message.py b/google/cloud/securitycenter_v1p1beta1/types/notification_message.py new file mode 100644 index 00000000..700d68eb --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/types/notification_message.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import resource as gcs_resource + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1p1beta1", manifest={"NotificationMessage",}, +) + + +class NotificationMessage(proto.Message): + r"""Security Command Center's Notification + + Attributes: + notification_config_name (str): + Name of the notification config that + generated current notification. + finding (~.gcs_finding.Finding): + If it's a Finding based notification config, + this field will be populated. + resource (~.gcs_resource.Resource): + The Cloud resource tied to the notification. + """ + + notification_config_name = proto.Field(proto.STRING, number=1) + + finding = proto.Field( + proto.MESSAGE, number=2, oneof="event", message=gcs_finding.Finding, + ) + + resource = proto.Field(proto.MESSAGE, number=3, message=gcs_resource.Resource,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py b/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py new file mode 100644 index 00000000..70fec686 --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py @@ -0,0 +1,89 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1p1beta1", manifest={"OrganizationSettings",}, +) + + +class OrganizationSettings(proto.Message): + r"""User specified settings that are attached to the Security + Command Center organization. + + Attributes: + name (str): + The relative resource name of the settings. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/organizationSettings". + enable_asset_discovery (bool): + A flag that indicates if Asset Discovery should be enabled. + If the flag is set to ``true``, then discovery of assets + will occur. If it is set to \`false, all historical assets + will remain, but discovery of future assets will not occur. + asset_discovery_config (~.organization_settings.OrganizationSettings.AssetDiscoveryConfig): + The configuration used for Asset Discovery + runs. + """ + + class AssetDiscoveryConfig(proto.Message): + r"""The configuration used for Asset Discovery runs. + + Attributes: + project_ids (Sequence[str]): + The project ids to use for filtering asset + discovery. + inclusion_mode (~.organization_settings.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): + The mode to use for filtering asset + discovery. + """ + + class InclusionMode(proto.Enum): + r"""The mode of inclusion when running Asset Discovery. Asset discovery + can be limited by explicitly identifying projects to be included or + excluded. If INCLUDE_ONLY is set, then only those projects within + the organization and their children are discovered during asset + discovery. If EXCLUDE is set, then projects that don't match those + projects are discovered during asset discovery. If neither are set, + then all projects within the organization are discovered during + asset discovery. + """ + INCLUSION_MODE_UNSPECIFIED = 0 + INCLUDE_ONLY = 1 + EXCLUDE = 2 + + project_ids = proto.RepeatedField(proto.STRING, number=1) + + inclusion_mode = proto.Field( + proto.ENUM, + number=2, + enum="OrganizationSettings.AssetDiscoveryConfig.InclusionMode", + ) + + name = proto.Field(proto.STRING, number=1) + + enable_asset_discovery = proto.Field(proto.BOOL, number=2) + + asset_discovery_config = proto.Field( + proto.MESSAGE, number=3, message=AssetDiscoveryConfig, + ) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/resource.py b/google/cloud/securitycenter_v1p1beta1/types/resource.py new file mode 100644 index 00000000..b29684ef --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/types/resource.py @@ -0,0 +1,56 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1p1beta1", manifest={"Resource",}, +) + + +class Resource(proto.Message): + r"""Information related to the Google Cloud resource. + + Attributes: + name (str): + The full resource name of the resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + project (str): + The full resource name of project that the + resource belongs to. + project_display_name (str): + The human readable name of project that the + resource belongs to. + parent (str): + The full resource name of resource's parent. + parent_display_name (str): + The human readable name of resource's parent. + """ + + name = proto.Field(proto.STRING, number=1) + + project = proto.Field(proto.STRING, number=2) + + project_display_name = proto.Field(proto.STRING, number=3) + + parent = proto.Field(proto.STRING, number=4) + + parent_display_name = proto.Field(proto.STRING, number=5) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py b/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py new file mode 100644 index 00000000..9c474a45 --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py @@ -0,0 +1,53 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +from google.protobuf import duration_pb2 as gp_duration # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1p1beta1", + manifest={"RunAssetDiscoveryResponse",}, +) + + +class RunAssetDiscoveryResponse(proto.Message): + r"""Response of asset discovery run + + Attributes: + state (~.run_asset_discovery_response.RunAssetDiscoveryResponse.State): + The state of an asset discovery run. + duration (~.gp_duration.Duration): + The duration between asset discovery run + start and end + """ + + class State(proto.Enum): + r"""The state of an asset discovery run.""" + STATE_UNSPECIFIED = 0 + COMPLETED = 1 + SUPERSEDED = 2 + TERMINATED = 3 + + state = proto.Field(proto.ENUM, number=1, enum=State,) + + duration = proto.Field(proto.MESSAGE, number=2, message=gp_duration.Duration,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/security_marks.py b/google/cloud/securitycenter_v1p1beta1/types/security_marks.py new file mode 100644 index 00000000..a7671f48 --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/types/security_marks.py @@ -0,0 +1,57 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1p1beta1", manifest={"SecurityMarks",}, +) + + +class SecurityMarks(proto.Message): + r"""User specified security marks that are attached to the parent + Security Command Center resource. Security marks are scoped + within a Security Command Center organization -- they can be + modified and viewed by all users who have proper permissions on + the organization. + + Attributes: + name (str): + The relative resource name of the SecurityMarks. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Examples: + "organizations/{organization_id}/assets/{asset_id}/securityMarks" + "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks". + marks (Sequence[~.security_marks.SecurityMarks.MarksEntry]): + Mutable user specified security marks belonging to the + parent resource. Constraints are as follows: + + - Keys and values are treated as case insensitive + - Keys must be between 1 - 256 characters (inclusive) + - Keys must be letters, numbers, underscores, or dashes + - Values have leading and trailing whitespace trimmed, + remaining characters must be between 1 - 4096 characters + (inclusive) + """ + + name = proto.Field(proto.STRING, number=1) + + marks = proto.MapField(proto.STRING, proto.STRING, number=2) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py b/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py new file mode 100644 index 00000000..c4cf2b57 --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py @@ -0,0 +1,1356 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +from google.cloud.securitycenter_v1p1beta1.types import asset as gcs_asset +from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding +from google.cloud.securitycenter_v1p1beta1.types import ( + notification_config as gcs_notification_config, +) +from google.cloud.securitycenter_v1p1beta1.types import ( + organization_settings as gcs_organization_settings, +) +from google.cloud.securitycenter_v1p1beta1.types import ( + security_marks as gcs_security_marks, +) +from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source +from google.protobuf import duration_pb2 as duration # type: ignore +from google.protobuf import field_mask_pb2 as gp_field_mask # type: ignore +from google.protobuf import struct_pb2 as struct # type: ignore +from google.protobuf import timestamp_pb2 as timestamp # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1p1beta1", + manifest={ + "CreateFindingRequest", + "CreateNotificationConfigRequest", + "CreateSourceRequest", + "DeleteNotificationConfigRequest", + "GetNotificationConfigRequest", + "GetOrganizationSettingsRequest", + "GetSourceRequest", + "GroupAssetsRequest", + "GroupAssetsResponse", + "GroupFindingsRequest", + "GroupFindingsResponse", + "GroupResult", + "ListNotificationConfigsRequest", + "ListNotificationConfigsResponse", + "ListSourcesRequest", + "ListSourcesResponse", + "ListAssetsRequest", + "ListAssetsResponse", + "ListFindingsRequest", + "ListFindingsResponse", + "SetFindingStateRequest", + "RunAssetDiscoveryRequest", + "UpdateFindingRequest", + "UpdateNotificationConfigRequest", + "UpdateOrganizationSettingsRequest", + "UpdateSourceRequest", + "UpdateSecurityMarksRequest", + }, +) + + +class CreateFindingRequest(proto.Message): + r"""Request message for creating a finding. + + Attributes: + parent (str): + Required. Resource name of the new finding's parent. Its + format should be + "organizations/[organization_id]/sources/[source_id]". + finding_id (str): + Required. Unique identifier provided by the + client within the parent scope. It must be + alphanumeric and less than or equal to 32 + characters and greater than 0 characters in + length. + finding (~.gcs_finding.Finding): + Required. The Finding being created. The name and + security_marks will be ignored as they are both output only + fields on this resource. + """ + + parent = proto.Field(proto.STRING, number=1) + + finding_id = proto.Field(proto.STRING, number=2) + + finding = proto.Field(proto.MESSAGE, number=3, message=gcs_finding.Finding,) + + +class CreateNotificationConfigRequest(proto.Message): + r"""Request message for creating a notification config. + + Attributes: + parent (str): + Required. Resource name of the new notification config's + parent. Its format is "organizations/[organization_id]". + config_id (str): + Required. + Unique identifier provided by the client within + the parent scope. It must be between 1 and 128 + characters, and contains alphanumeric + characters, underscores or hyphens only. + notification_config (~.gcs_notification_config.NotificationConfig): + Required. The notification config being + created. The name and the service account will + be ignored as they are both output only fields + on this resource. + """ + + parent = proto.Field(proto.STRING, number=1) + + config_id = proto.Field(proto.STRING, number=2) + + notification_config = proto.Field( + proto.MESSAGE, number=3, message=gcs_notification_config.NotificationConfig, + ) + + +class CreateSourceRequest(proto.Message): + r"""Request message for creating a source. + + Attributes: + parent (str): + Required. Resource name of the new source's parent. Its + format should be "organizations/[organization_id]". + source (~.gcs_source.Source): + Required. The Source being created, only the display_name + and description will be used. All other fields will be + ignored. + """ + + parent = proto.Field(proto.STRING, number=1) + + source = proto.Field(proto.MESSAGE, number=2, message=gcs_source.Source,) + + +class DeleteNotificationConfigRequest(proto.Message): + r"""Request message for deleting a notification config. + + Attributes: + name (str): + Required. Name of the notification config to delete. Its + format is + "organizations/[organization_id]/notificationConfigs/[config_id]". + """ + + name = proto.Field(proto.STRING, number=1) + + +class GetNotificationConfigRequest(proto.Message): + r"""Request message for getting a notification config. + + Attributes: + name (str): + Required. Name of the notification config to get. Its format + is + "organizations/[organization_id]/notificationConfigs/[config_id]". + """ + + name = proto.Field(proto.STRING, number=1) + + +class GetOrganizationSettingsRequest(proto.Message): + r"""Request message for getting organization settings. + + Attributes: + name (str): + Required. Name of the organization to get organization + settings for. Its format is + "organizations/[organization_id]/organizationSettings". + """ + + name = proto.Field(proto.STRING, number=1) + + +class GetSourceRequest(proto.Message): + r"""Request message for getting a source. + + Attributes: + name (str): + Required. Relative resource name of the source. Its format + is "organizations/[organization_id]/source/[source_id]". + """ + + name = proto.Field(proto.STRING, number=1) + + +class GroupAssetsRequest(proto.Message): + r"""Request message for grouping by assets. + + Attributes: + parent (str): + Required. Name of the organization to groupBy. Its format is + "organizations/[organization_id]". + filter (str): + Expression that defines the filter to apply across assets. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the Asset + resource. Examples include: + + - name + - security_center_properties.resource_name + - resource_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``update_time = "2019-06-10T16:07:18-07:00"`` + ``update_time = 1560208038000`` + + - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``create_time = "2019-06-10T16:07:18-07:00"`` + ``create_time = 1560208038000`` + + - iam_policy.policy_blob: ``=``, ``:`` + + - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, + ``<=`` + + - security_marks.marks: ``=``, ``:`` + + - security_center_properties.resource_name: ``=``, ``:`` + + - security_center_properties.resource_name_display_name: + ``=``, ``:`` + + - security_center_properties.resource_type: ``=``, ``:`` + + - security_center_properties.resource_parent: ``=``, ``:`` + + - security_center_properties.resource_parent_display_name: + ``=``, ``:`` + + - security_center_properties.resource_project: ``=``, ``:`` + + - security_center_properties.resource_project_display_name: + ``=``, ``:`` + + - security_center_properties.resource_owners: ``=``, ``:`` + + For example, ``resource_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based on a + property existing: ``resource_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-resource_properties.my_property : ""`` + group_by (str): + Required. Expression that defines what assets fields to use + for grouping. The string value should follow SQL syntax: + comma separated list of fields. For example: + "security_center_properties.resource_project,security_center_properties.project". + + The following fields are supported when compare_duration is + not set: + + - security_center_properties.resource_project + - security_center_properties.resource_project_display_name + - security_center_properties.resource_type + - security_center_properties.resource_parent + - security_center_properties.resource_parent_display_name + + The following fields are supported when compare_duration is + set: + + - security_center_properties.resource_type + - security_center_properties.resource_project_display_name + - security_center_properties.resource_parent_display_name + compare_duration (~.duration.Duration): + When compare_duration is set, the GroupResult's + "state_change" property is updated to indicate whether the + asset was added, removed, or remained present during the + compare_duration period of time that precedes the read_time. + This is the time between (read_time - compare_duration) and + read_time. + + The state change value is derived based on the presence of + the asset at the two points in time. Intermediate state + changes between the two times don't affect the result. For + example, the results aren't affected if the asset is removed + and re-created again. + + Possible "state_change" values when compare_duration is + specified: + + - "ADDED": indicates that the asset was not present at the + start of compare_duration, but present at reference_time. + - "REMOVED": indicates that the asset was present at the + start of compare_duration, but not present at + reference_time. + - "ACTIVE": indicates that the asset was present at both + the start and the end of the time period defined by + compare_duration and reference_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all assets present at read_time. + + If this field is set then ``state_change`` must be a + specified field in ``group_by``. + read_time (~.timestamp.Timestamp): + Time used as a reference point when filtering + assets. The filter is limited to assets existing + at the supplied time and their values are those + at that specific time. Absence of this field + will default to the API's version of NOW. + page_token (str): + The value returned by the last ``GroupAssetsResponse``; + indicates that this is a continuation of a prior + ``GroupAssets`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field(proto.STRING, number=1) + + filter = proto.Field(proto.STRING, number=2) + + group_by = proto.Field(proto.STRING, number=3) + + compare_duration = proto.Field(proto.MESSAGE, number=4, message=duration.Duration,) + + read_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) + + page_token = proto.Field(proto.STRING, number=7) + + page_size = proto.Field(proto.INT32, number=8) + + +class GroupAssetsResponse(proto.Message): + r"""Response message for grouping by assets. + + Attributes: + group_by_results (Sequence[~.securitycenter_service.GroupResult]): + Group results. There exists an element for + each existing unique combination of + property/values. The element contains a count + for the number of times those specific + property/values appear. + read_time (~.timestamp.Timestamp): + Time used for executing the groupBy request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of results matching the + query. + """ + + @property + def raw_page(self): + return self + + group_by_results = proto.RepeatedField( + proto.MESSAGE, number=1, message="GroupResult", + ) + + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + next_page_token = proto.Field(proto.STRING, number=3) + + total_size = proto.Field(proto.INT32, number=4) + + +class GroupFindingsRequest(proto.Message): + r"""Request message for grouping by findings. + + Attributes: + parent (str): + Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]". To + groupBy across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/- + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - source_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - parent: ``=``, ``:`` + + - resource_name: ``=``, ``:`` + + - state: ``=``, ``:`` + + - category: ``=``, ``:`` + + - external_uri: ``=``, ``:`` + + - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``event_time = "2019-06-10T16:07:18-07:00"`` + ``event_time = 1560208038000`` + + - security_marks.marks: ``=``, ``:`` + + - source_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, + ``<=`` + + For example, ``source_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based on a + property existing: ``source_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-source_properties.my_property : ""`` + group_by (str): + Required. Expression that defines what assets fields to use + for grouping (including ``state_change``). The string value + should follow SQL syntax: comma separated list of fields. + For example: "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + + The following fields are supported when compare_duration is + set: + + - state_change + read_time (~.timestamp.Timestamp): + Time used as a reference point when filtering + findings. The filter is limited to findings + existing at the supplied time and their values + are those at that specific time. Absence of this + field will default to the API's version of NOW. + compare_duration (~.duration.Duration): + When compare_duration is set, the GroupResult's + "state_change" attribute is updated to indicate whether the + finding had its state changed, the finding's state remained + unchanged, or if the finding was added during the + compare_duration period of time that precedes the read_time. + This is the time between (read_time - compare_duration) and + read_time. + + The state_change value is derived based on the presence and + state of the finding at the two points in time. Intermediate + state changes between the two times don't affect the result. + For example, the results aren't affected if the finding is + made inactive and then active again. + + Possible "state_change" values when compare_duration is + specified: + + - "CHANGED": indicates that the finding was present and + matched the given filter at the start of + compare_duration, but changed its state at read_time. + - "UNCHANGED": indicates that the finding was present and + matched the given filter at the start of compare_duration + and did not change state at read_time. + - "ADDED": indicates that the finding did not match the + given filter or was not present at the start of + compare_duration, but was present at read_time. + - "REMOVED": indicates that the finding was present and + matched the filter at the start of compare_duration, but + did not match the filter at read_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all findings present at read_time. + + If this field is set then ``state_change`` must be a + specified field in ``group_by``. + page_token (str): + The value returned by the last ``GroupFindingsResponse``; + indicates that this is a continuation of a prior + ``GroupFindings`` call, and that the system should return + the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field(proto.STRING, number=1) + + filter = proto.Field(proto.STRING, number=2) + + group_by = proto.Field(proto.STRING, number=3) + + read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) + + compare_duration = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) + + page_token = proto.Field(proto.STRING, number=7) + + page_size = proto.Field(proto.INT32, number=8) + + +class GroupFindingsResponse(proto.Message): + r"""Response message for group by findings. + + Attributes: + group_by_results (Sequence[~.securitycenter_service.GroupResult]): + Group results. There exists an element for + each existing unique combination of + property/values. The element contains a count + for the number of times those specific + property/values appear. + read_time (~.timestamp.Timestamp): + Time used for executing the groupBy request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of results matching the + query. + """ + + @property + def raw_page(self): + return self + + group_by_results = proto.RepeatedField( + proto.MESSAGE, number=1, message="GroupResult", + ) + + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + next_page_token = proto.Field(proto.STRING, number=3) + + total_size = proto.Field(proto.INT32, number=4) + + +class GroupResult(proto.Message): + r"""Result containing the properties and count of a groupBy + request. + + Attributes: + properties (Sequence[~.securitycenter_service.GroupResult.PropertiesEntry]): + Properties matching the groupBy fields in the + request. + count (int): + Total count of resources for the given + properties. + """ + + properties = proto.MapField( + proto.STRING, proto.MESSAGE, number=1, message=struct.Value, + ) + + count = proto.Field(proto.INT64, number=2) + + +class ListNotificationConfigsRequest(proto.Message): + r"""Request message for listing notification configs. + + Attributes: + parent (str): + Required. Name of the organization to list notification + configs. Its format is "organizations/[organization_id]". + page_token (str): + The value returned by the last + ``ListNotificationConfigsResponse``; indicates that this is + a continuation of a prior ``ListNotificationConfigs`` call, + and that the system should return the next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_token = proto.Field(proto.STRING, number=2) + + page_size = proto.Field(proto.INT32, number=3) + + +class ListNotificationConfigsResponse(proto.Message): + r"""Response message for listing notification configs. + + Attributes: + notification_configs (Sequence[~.gcs_notification_config.NotificationConfig]): + Notification configs belonging to the + requested parent. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + notification_configs = proto.RepeatedField( + proto.MESSAGE, number=1, message=gcs_notification_config.NotificationConfig, + ) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class ListSourcesRequest(proto.Message): + r"""Request message for listing sources. + + Attributes: + parent (str): + Required. Resource name of the parent of sources to list. + Its format should be "organizations/[organization_id]". + page_token (str): + The value returned by the last ``ListSourcesResponse``; + indicates that this is a continuation of a prior + ``ListSources`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field(proto.STRING, number=1) + + page_token = proto.Field(proto.STRING, number=2) + + page_size = proto.Field(proto.INT32, number=7) + + +class ListSourcesResponse(proto.Message): + r"""Response message for listing sources. + + Attributes: + sources (Sequence[~.gcs_source.Source]): + Sources belonging to the requested parent. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + """ + + @property + def raw_page(self): + return self + + sources = proto.RepeatedField(proto.MESSAGE, number=1, message=gcs_source.Source,) + + next_page_token = proto.Field(proto.STRING, number=2) + + +class ListAssetsRequest(proto.Message): + r"""Request message for listing assets. + + Attributes: + parent (str): + Required. Name of the organization assets should belong to. + Its format is "organizations/[organization_id]". + filter (str): + Expression that defines the filter to apply across assets. + The expression is a list of zero or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. The fields map to those defined in the Asset + resource. Examples include: + + - name + - security_center_properties.resource_name + - resource_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following are the allowed field and operator + combinations: + + - name: ``=`` + + - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``update_time = "2019-06-10T16:07:18-07:00"`` + ``update_time = 1560208038000`` + + - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an + RFC3339 string. Examples: + ``create_time = "2019-06-10T16:07:18-07:00"`` + ``create_time = 1560208038000`` + + - iam_policy.policy_blob: ``=``, ``:`` + + - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, + ``<=`` + + - security_marks.marks: ``=``, ``:`` + + - security_center_properties.resource_name: ``=``, ``:`` + + - security_center_properties.resource_display_name: ``=``, + ``:`` + + - security_center_properties.resource_type: ``=``, ``:`` + + - security_center_properties.resource_parent: ``=``, ``:`` + + - security_center_properties.resource_parent_display_name: + ``=``, ``:`` + + - security_center_properties.resource_project: ``=``, ``:`` + + - security_center_properties.resource_project_display_name: + ``=``, ``:`` + + - security_center_properties.resource_owners: ``=``, ``:`` + + For example, ``resource_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based on a + property existing: ``resource_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-resource_properties.my_property : ""`` + order_by (str): + Expression that defines what fields and order to use for + sorting. The string value should follow SQL syntax: comma + separated list of fields. For example: + "name,resource_properties.a_property". The default sorting + order is ascending. To specify descending order for a field, + a suffix " desc" should be appended to the field name. For + example: "name desc,resource_properties.a_property". + Redundant space characters in the syntax are insignificant. + "name desc,resource_properties.a_property" and " name desc , + resource_properties.a_property " are equivalent. + + The following fields are supported: name update_time + resource_properties security_marks.marks + security_center_properties.resource_name + security_center_properties.resource_display_name + security_center_properties.resource_parent + security_center_properties.resource_parent_display_name + security_center_properties.resource_project + security_center_properties.resource_project_display_name + security_center_properties.resource_type + read_time (~.timestamp.Timestamp): + Time used as a reference point when filtering + assets. The filter is limited to assets existing + at the supplied time and their values are those + at that specific time. Absence of this field + will default to the API's version of NOW. + compare_duration (~.duration.Duration): + When compare_duration is set, the ListAssetsResult's + "state_change" attribute is updated to indicate whether the + asset was added, removed, or remained present during the + compare_duration period of time that precedes the read_time. + This is the time between (read_time - compare_duration) and + read_time. + + The state_change value is derived based on the presence of + the asset at the two points in time. Intermediate state + changes between the two times don't affect the result. For + example, the results aren't affected if the asset is removed + and re-created again. + + Possible "state_change" values when compare_duration is + specified: + + - "ADDED": indicates that the asset was not present at the + start of compare_duration, but present at read_time. + - "REMOVED": indicates that the asset was present at the + start of compare_duration, but not present at read_time. + - "ACTIVE": indicates that the asset was present at both + the start and the end of the time period defined by + compare_duration and read_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all assets present at read_time. + field_mask (~.gp_field_mask.FieldMask): + Optional. + A field mask to specify the ListAssetsResult + fields to be listed in the response. + An empty field mask will list all fields. + page_token (str): + The value returned by the last ``ListAssetsResponse``; + indicates that this is a continuation of a prior + ``ListAssets`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field(proto.STRING, number=1) + + filter = proto.Field(proto.STRING, number=2) + + order_by = proto.Field(proto.STRING, number=3) + + read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) + + compare_duration = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) + + field_mask = proto.Field(proto.MESSAGE, number=7, message=gp_field_mask.FieldMask,) + + page_token = proto.Field(proto.STRING, number=8) + + page_size = proto.Field(proto.INT32, number=9) + + +class ListAssetsResponse(proto.Message): + r"""Response message for listing assets. + + Attributes: + list_assets_results (Sequence[~.securitycenter_service.ListAssetsResponse.ListAssetsResult]): + Assets matching the list request. + read_time (~.timestamp.Timestamp): + Time used for executing the list request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of assets matching the + query. + """ + + class ListAssetsResult(proto.Message): + r"""Result containing the Asset and its State. + + Attributes: + asset (~.gcs_asset.Asset): + Asset matching the search request. + state_change (~.securitycenter_service.ListAssetsResponse.ListAssetsResult.StateChange): + State change of the asset between the points + in time. + """ + + class StateChange(proto.Enum): + r"""The change in state of the asset. + + When querying across two points in time this describes the change + between the two points: ADDED, REMOVED, or ACTIVE. If there was no + compare_duration supplied in the request the state change will be: + UNUSED + """ + UNUSED = 0 + ADDED = 1 + REMOVED = 2 + ACTIVE = 3 + + asset = proto.Field(proto.MESSAGE, number=1, message=gcs_asset.Asset,) + + state_change = proto.Field( + proto.ENUM, + number=2, + enum="ListAssetsResponse.ListAssetsResult.StateChange", + ) + + @property + def raw_page(self): + return self + + list_assets_results = proto.RepeatedField( + proto.MESSAGE, number=1, message=ListAssetsResult, + ) + + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + next_page_token = proto.Field(proto.STRING, number=3) + + total_size = proto.Field(proto.INT32, number=4) + + +class ListFindingsRequest(proto.Message): + r"""Request message for listing findings. + + Attributes: + parent (str): + Required. Name of the source the findings belong to. Its + format is + "organizations/[organization_id]/sources/[source_id]". To + list across all sources provide a source_id of ``-``. For + example: organizations/{organization_id}/sources/- + filter (str): + Expression that defines the filter to apply across findings. + The expression is a list of one or more restrictions + combined via logical operators ``AND`` and ``OR``. + Parentheses are supported, and ``OR`` has higher precedence + than ``AND``. + + Restrictions have the form `` `` + and may have a ``-`` character in front of them to indicate + negation. Examples include: + + - name + - source_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + name: ``=`` parent: ``=``, ``:`` resource_name: ``=``, ``:`` + state: ``=``, ``:`` category: ``=``, ``:`` external_uri: + ``=``, ``:`` event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an RFC3339 + string. Examples: + ``event_time = "2019-06-10T16:07:18-07:00"`` + ``event_time = 1560208038000`` + + security_marks.marks: ``=``, ``:`` source_properties: ``=``, + ``:``, ``>``, ``<``, ``>=``, ``<=`` + + For example, ``source_properties.size = 100`` is a valid + filter string. + + Use a partial match on the empty string to filter based on a + property existing: ``source_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter + based on a property not existing: + ``-source_properties.my_property : ""`` + order_by (str): + Expression that defines what fields and order to use for + sorting. The string value should follow SQL syntax: comma + separated list of fields. For example: + "name,resource_properties.a_property". The default sorting + order is ascending. To specify descending order for a field, + a suffix " desc" should be appended to the field name. For + example: "name desc,source_properties.a_property". Redundant + space characters in the syntax are insignificant. "name + desc,source_properties.a_property" and " name desc , + source_properties.a_property " are equivalent. + + The following fields are supported: name parent state + category resource_name event_time source_properties + security_marks.marks + read_time (~.timestamp.Timestamp): + Time used as a reference point when filtering + findings. The filter is limited to findings + existing at the supplied time and their values + are those at that specific time. Absence of this + field will default to the API's version of NOW. + compare_duration (~.duration.Duration): + When compare_duration is set, the ListFindingsResult's + "state_change" attribute is updated to indicate whether the + finding had its state changed, the finding's state remained + unchanged, or if the finding was added in any state during + the compare_duration period of time that precedes the + read_time. This is the time between (read_time - + compare_duration) and read_time. + + The state_change value is derived based on the presence and + state of the finding at the two points in time. Intermediate + state changes between the two times don't affect the result. + For example, the results aren't affected if the finding is + made inactive and then active again. + + Possible "state_change" values when compare_duration is + specified: + + - "CHANGED": indicates that the finding was present and + matched the given filter at the start of + compare_duration, but changed its state at read_time. + - "UNCHANGED": indicates that the finding was present and + matched the given filter at the start of compare_duration + and did not change state at read_time. + - "ADDED": indicates that the finding did not match the + given filter or was not present at the start of + compare_duration, but was present at read_time. + - "REMOVED": indicates that the finding was present and + matched the filter at the start of compare_duration, but + did not match the filter at read_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set + for all findings present at read_time. + field_mask (~.gp_field_mask.FieldMask): + Optional. + A field mask to specify the Finding fields to be + listed in the response. An empty field mask will + list all fields. + page_token (str): + The value returned by the last ``ListFindingsResponse``; + indicates that this is a continuation of a prior + ``ListFindings`` call, and that the system should return the + next page of data. + page_size (int): + The maximum number of results to return in a + single response. Default is 10, minimum is 1, + maximum is 1000. + """ + + parent = proto.Field(proto.STRING, number=1) + + filter = proto.Field(proto.STRING, number=2) + + order_by = proto.Field(proto.STRING, number=3) + + read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) + + compare_duration = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) + + field_mask = proto.Field(proto.MESSAGE, number=7, message=gp_field_mask.FieldMask,) + + page_token = proto.Field(proto.STRING, number=8) + + page_size = proto.Field(proto.INT32, number=9) + + +class ListFindingsResponse(proto.Message): + r"""Response message for listing findings. + + Attributes: + list_findings_results (Sequence[~.securitycenter_service.ListFindingsResponse.ListFindingsResult]): + Findings matching the list request. + read_time (~.timestamp.Timestamp): + Time used for executing the list request. + next_page_token (str): + Token to retrieve the next page of results, + or empty if there are no more results. + total_size (int): + The total number of findings matching the + query. + """ + + class ListFindingsResult(proto.Message): + r"""Result containing the Finding and its StateChange. + + Attributes: + finding (~.gcs_finding.Finding): + Finding matching the search request. + state_change (~.securitycenter_service.ListFindingsResponse.ListFindingsResult.StateChange): + State change of the finding between the + points in time. + resource (~.securitycenter_service.ListFindingsResponse.ListFindingsResult.Resource): + Output only. Resource that is associated with + this finding. + """ + + class StateChange(proto.Enum): + r"""The change in state of the finding. + + When querying across two points in time this describes the change in + the finding between the two points: CHANGED, UNCHANGED, ADDED, or + REMOVED. Findings can not be deleted, so REMOVED implies that the + finding at timestamp does not match the filter specified, but it did + at timestamp - compare_duration. If there was no compare_duration + supplied in the request the state change will be: UNUSED + """ + UNUSED = 0 + CHANGED = 1 + UNCHANGED = 2 + ADDED = 3 + REMOVED = 4 + + class Resource(proto.Message): + r"""Information related to the Google Cloud resource that is + associated with this finding. + + Attributes: + name (str): + The full resource name of the resource. See: + https://cloud.google.com/apis/design/resource_names#full_resource_name + project_name (str): + The full resource name of project that the + resource belongs to. + project_display_name (str): + The human readable name of project that the + resource belongs to. + parent_name (str): + The full resource name of resource's parent. + parent_display_name (str): + The human readable name of resource's parent. + """ + + name = proto.Field(proto.STRING, number=1) + + project_name = proto.Field(proto.STRING, number=2) + + project_display_name = proto.Field(proto.STRING, number=3) + + parent_name = proto.Field(proto.STRING, number=4) + + parent_display_name = proto.Field(proto.STRING, number=5) + + finding = proto.Field(proto.MESSAGE, number=1, message=gcs_finding.Finding,) + + state_change = proto.Field( + proto.ENUM, + number=2, + enum="ListFindingsResponse.ListFindingsResult.StateChange", + ) + + resource = proto.Field( + proto.MESSAGE, + number=3, + message="ListFindingsResponse.ListFindingsResult.Resource", + ) + + @property + def raw_page(self): + return self + + list_findings_results = proto.RepeatedField( + proto.MESSAGE, number=1, message=ListFindingsResult, + ) + + read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) + + next_page_token = proto.Field(proto.STRING, number=3) + + total_size = proto.Field(proto.INT32, number=4) + + +class SetFindingStateRequest(proto.Message): + r"""Request message for updating a finding's state. + + Attributes: + name (str): + Required. The relative resource name of the finding. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". + state (~.gcs_finding.Finding.State): + Required. The desired State of the finding. + start_time (~.timestamp.Timestamp): + Required. The time at which the updated state + takes effect. + """ + + name = proto.Field(proto.STRING, number=1) + + state = proto.Field(proto.ENUM, number=2, enum=gcs_finding.Finding.State,) + + start_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + + +class RunAssetDiscoveryRequest(proto.Message): + r"""Request message for running asset discovery for an + organization. + + Attributes: + parent (str): + Required. Name of the organization to run asset discovery + for. Its format is "organizations/[organization_id]". + """ + + parent = proto.Field(proto.STRING, number=1) + + +class UpdateFindingRequest(proto.Message): + r"""Request message for updating or creating a finding. + + Attributes: + finding (~.gcs_finding.Finding): + Required. The finding resource to update or create if it + does not already exist. parent, security_marks, and + update_time will be ignored. + + In the case of creation, the finding id portion of the name + must be alphanumeric and less than or equal to 32 characters + and greater than 0 characters in length. + update_mask (~.gp_field_mask.FieldMask): + The FieldMask to use when updating the finding resource. + This field should not be specified when creating a finding. + + When updating a finding, an empty mask is treated as + updating all mutable fields and replacing source_properties. + Individual source_properties can be added/updated by using + "source_properties." in the field mask. + """ + + finding = proto.Field(proto.MESSAGE, number=1, message=gcs_finding.Finding,) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + + +class UpdateNotificationConfigRequest(proto.Message): + r"""Request message for updating a notification config. + + Attributes: + notification_config (~.gcs_notification_config.NotificationConfig): + Required. The notification config to update. + update_mask (~.gp_field_mask.FieldMask): + The FieldMask to use when updating the + notification config. + If empty all mutable fields will be updated. + """ + + notification_config = proto.Field( + proto.MESSAGE, number=1, message=gcs_notification_config.NotificationConfig, + ) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + + +class UpdateOrganizationSettingsRequest(proto.Message): + r"""Request message for updating an organization's settings. + + Attributes: + organization_settings (~.gcs_organization_settings.OrganizationSettings): + Required. The organization settings resource + to update. + update_mask (~.gp_field_mask.FieldMask): + The FieldMask to use when updating the + settings resource. + If empty all mutable fields will be updated. + """ + + organization_settings = proto.Field( + proto.MESSAGE, number=1, message=gcs_organization_settings.OrganizationSettings, + ) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + + +class UpdateSourceRequest(proto.Message): + r"""Request message for updating a source. + + Attributes: + source (~.gcs_source.Source): + Required. The source resource to update. + update_mask (~.gp_field_mask.FieldMask): + The FieldMask to use when updating the source + resource. + If empty all mutable fields will be updated. + """ + + source = proto.Field(proto.MESSAGE, number=1, message=gcs_source.Source,) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + + +class UpdateSecurityMarksRequest(proto.Message): + r"""Request message for updating a SecurityMarks resource. + + Attributes: + security_marks (~.gcs_security_marks.SecurityMarks): + Required. The security marks resource to + update. + update_mask (~.gp_field_mask.FieldMask): + The FieldMask to use when updating the security marks + resource. + + The field mask must not contain duplicate fields. If empty + or set to "marks", all marks will be replaced. Individual + marks can be updated using "marks.". + start_time (~.timestamp.Timestamp): + The time at which the updated SecurityMarks + take effect. If not set uses current server + time. Updates will be applied to the + SecurityMarks that are active immediately + preceding this time. + """ + + security_marks = proto.Field( + proto.MESSAGE, number=1, message=gcs_security_marks.SecurityMarks, + ) + + update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) + + start_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/source.py b/google/cloud/securitycenter_v1p1beta1/types/source.py new file mode 100644 index 00000000..90a4ad7d --- /dev/null +++ b/google/cloud/securitycenter_v1p1beta1/types/source.py @@ -0,0 +1,64 @@ +# -*- coding: utf-8 -*- + +# Copyright 2020 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 proto # type: ignore + + +__protobuf__ = proto.module( + package="google.cloud.securitycenter.v1p1beta1", manifest={"Source",}, +) + + +class Source(proto.Message): + r"""Security Command Center finding source. A finding source + is an entity or a mechanism that can produce a finding. A source + is like a container of findings that come from the same scanner, + logger, monitor, etc. + + Attributes: + name (str): + The relative resource name of this source. See: + https://cloud.google.com/apis/design/resource_names#relative_resource_name + Example: + "organizations/{organization_id}/sources/{source_id}". + display_name (str): + The source's display name. + A source's display name must be unique amongst + its siblings, for example, two sources with the + same parent can't share the same display name. + The display name must have a length between 1 + and 64 characters (inclusive). + description (str): + The description of the source (max of 1024 + characters). Example: + "Web Security Scanner is a web security scanner + for common vulnerabilities in App Engine + applications. It can automatically scan and + detect four common vulnerabilities, including + cross-site-scripting (XSS), Flash injection, + mixed content (HTTP in HTTPS), and + outdated/insecure libraries.". + """ + + name = proto.Field(proto.STRING, number=1) + + display_name = proto.Field(proto.STRING, number=2) + + description = proto.Field(proto.STRING, number=3) + + +__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/synth.metadata b/synth.metadata index 7d71d26b..2c0b66bb 100644 --- a/synth.metadata +++ b/synth.metadata @@ -11,8 +11,8 @@ "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "599ede9ebdeb33a91be48748f5f83ec13e7e692c", - "internalRef": "323062460" + "sha": "6a813acf535e4746fa4a135ce23547bb6425c26d", + "internalRef": "323472217" } }, { diff --git a/tests/unit/gapic/v1/test_security_center_client_v1.py b/tests/unit/gapic/v1/test_security_center_client_v1.py index 96cf1bd2..dbecf0c9 100644 --- a/tests/unit/gapic/v1/test_security_center_client_v1.py +++ b/tests/unit/gapic/v1/test_security_center_client_v1.py @@ -74,6 +74,196 @@ class CustomException(Exception): class TestSecurityCenterClient(object): + def test_get_iam_policy(self): + # Setup Expected Response + version = 351608024 + etag = b"21" + expected_response = {"version": version, "etag": etag} + expected_response = policy_pb2.Policy(**expected_response) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + patch = mock.patch("google.api_core.grpc_helpers.create_channel") + with patch as create_channel: + create_channel.return_value = channel + client = securitycenter_v1.SecurityCenterClient() + + # Setup Request + resource = "resource-341064690" + + response = client.get_iam_policy(resource) + assert expected_response == response + + assert len(channel.requests) == 1 + expected_request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_get_iam_policy_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + patch = mock.patch("google.api_core.grpc_helpers.create_channel") + with patch as create_channel: + create_channel.return_value = channel + client = securitycenter_v1.SecurityCenterClient() + + # Setup request + resource = "resource-341064690" + + with pytest.raises(CustomException): + client.get_iam_policy(resource) + + def test_group_assets(self): + # Setup Expected Response + next_page_token = "" + total_size = 705419236 + group_by_results_element = {} + group_by_results = [group_by_results_element] + expected_response = { + "next_page_token": next_page_token, + "total_size": total_size, + "group_by_results": group_by_results, + } + expected_response = securitycenter_service_pb2.GroupAssetsResponse( + **expected_response + ) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + patch = mock.patch("google.api_core.grpc_helpers.create_channel") + with patch as create_channel: + create_channel.return_value = channel + client = securitycenter_v1.SecurityCenterClient() + + # Setup Request + parent = client.organization_path("[ORGANIZATION]") + group_by = "groupBy506361367" + + paged_list_response = client.group_assets(parent, group_by) + resources = list(paged_list_response) + assert len(resources) == 1 + + assert expected_response.group_by_results[0] == resources[0] + + assert len(channel.requests) == 1 + expected_request = securitycenter_service_pb2.GroupAssetsRequest( + parent=parent, group_by=group_by + ) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_group_assets_exception(self): + channel = ChannelStub(responses=[CustomException()]) + patch = mock.patch("google.api_core.grpc_helpers.create_channel") + with patch as create_channel: + create_channel.return_value = channel + client = securitycenter_v1.SecurityCenterClient() + + # Setup request + parent = client.organization_path("[ORGANIZATION]") + group_by = "groupBy506361367" + + paged_list_response = client.group_assets(parent, group_by) + with pytest.raises(CustomException): + list(paged_list_response) + + def test_group_findings(self): + # Setup Expected Response + next_page_token = "" + total_size = 705419236 + group_by_results_element = {} + group_by_results = [group_by_results_element] + expected_response = { + "next_page_token": next_page_token, + "total_size": total_size, + "group_by_results": group_by_results, + } + expected_response = securitycenter_service_pb2.GroupFindingsResponse( + **expected_response + ) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + patch = mock.patch("google.api_core.grpc_helpers.create_channel") + with patch as create_channel: + create_channel.return_value = channel + client = securitycenter_v1.SecurityCenterClient() + + # Setup Request + parent = client.source_path("[ORGANIZATION]", "[SOURCE]") + group_by = "groupBy506361367" + + paged_list_response = client.group_findings(parent, group_by) + resources = list(paged_list_response) + assert len(resources) == 1 + + assert expected_response.group_by_results[0] == resources[0] + + assert len(channel.requests) == 1 + expected_request = securitycenter_service_pb2.GroupFindingsRequest( + parent=parent, group_by=group_by + ) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_group_findings_exception(self): + channel = ChannelStub(responses=[CustomException()]) + patch = mock.patch("google.api_core.grpc_helpers.create_channel") + with patch as create_channel: + create_channel.return_value = channel + client = securitycenter_v1.SecurityCenterClient() + + # Setup request + parent = client.source_path("[ORGANIZATION]", "[SOURCE]") + group_by = "groupBy506361367" + + paged_list_response = client.group_findings(parent, group_by) + with pytest.raises(CustomException): + list(paged_list_response) + + def test_test_iam_permissions(self): + # Setup Expected Response + expected_response = {} + expected_response = iam_policy_pb2.TestIamPermissionsResponse( + **expected_response + ) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + patch = mock.patch("google.api_core.grpc_helpers.create_channel") + with patch as create_channel: + create_channel.return_value = channel + client = securitycenter_v1.SecurityCenterClient() + + # Setup Request + resource = "resource-341064690" + permissions = [] + + response = client.test_iam_permissions(resource, permissions) + assert expected_response == response + + assert len(channel.requests) == 1 + expected_request = iam_policy_pb2.TestIamPermissionsRequest( + resource=resource, permissions=permissions + ) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_test_iam_permissions_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + patch = mock.patch("google.api_core.grpc_helpers.create_channel") + with patch as create_channel: + create_channel.return_value = channel + client = securitycenter_v1.SecurityCenterClient() + + # Setup request + resource = "resource-341064690" + permissions = [] + + with pytest.raises(CustomException): + client.test_iam_permissions(resource, permissions) + def test_create_source(self): # Setup Expected Response name = "name3373707" @@ -269,45 +459,6 @@ def test_delete_notification_config_exception(self): with pytest.raises(CustomException): client.delete_notification_config(name) - def test_get_iam_policy(self): - # Setup Expected Response - version = 351608024 - etag = b"21" - expected_response = {"version": version, "etag": etag} - expected_response = policy_pb2.Policy(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - resource = "resource-341064690" - - response = client.get_iam_policy(resource) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_iam_policy_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - resource = "resource-341064690" - - with pytest.raises(CustomException): - client.get_iam_policy(resource) - def test_get_notification_config(self): # Setup Expected Response name_2 = "name2-1052831874" @@ -452,114 +603,6 @@ def test_get_source_exception(self): with pytest.raises(CustomException): client.get_source(name) - def test_group_assets(self): - # Setup Expected Response - next_page_token = "" - total_size = 705419236 - group_by_results_element = {} - group_by_results = [group_by_results_element] - expected_response = { - "next_page_token": next_page_token, - "total_size": total_size, - "group_by_results": group_by_results, - } - expected_response = securitycenter_service_pb2.GroupAssetsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - parent = client.organization_path("[ORGANIZATION]") - group_by = "groupBy506361367" - - paged_list_response = client.group_assets(parent, group_by) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.group_by_results[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.GroupAssetsRequest( - parent=parent, group_by=group_by - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_group_assets_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - parent = client.organization_path("[ORGANIZATION]") - group_by = "groupBy506361367" - - paged_list_response = client.group_assets(parent, group_by) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_group_findings(self): - # Setup Expected Response - next_page_token = "" - total_size = 705419236 - group_by_results_element = {} - group_by_results = [group_by_results_element] - expected_response = { - "next_page_token": next_page_token, - "total_size": total_size, - "group_by_results": group_by_results, - } - expected_response = securitycenter_service_pb2.GroupFindingsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - parent = client.source_path("[ORGANIZATION]", "[SOURCE]") - group_by = "groupBy506361367" - - paged_list_response = client.group_findings(parent, group_by) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.group_by_results[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.GroupFindingsRequest( - parent=parent, group_by=group_by - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_group_findings_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - parent = client.source_path("[ORGANIZATION]", "[SOURCE]") - group_by = "groupBy506361367" - - paged_list_response = client.group_findings(parent, group_by) - with pytest.raises(CustomException): - list(paged_list_response) - def test_list_assets(self): # Setup Expected Response next_page_token = "" @@ -906,49 +949,6 @@ def test_set_iam_policy_exception(self): with pytest.raises(CustomException): client.set_iam_policy(resource, policy) - def test_test_iam_permissions(self): - # Setup Expected Response - expected_response = {} - expected_response = iam_policy_pb2.TestIamPermissionsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - resource = "resource-341064690" - permissions = [] - - response = client.test_iam_permissions(resource, permissions) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = iam_policy_pb2.TestIamPermissionsRequest( - resource=resource, permissions=permissions - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_test_iam_permissions_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - resource = "resource-341064690" - permissions = [] - - with pytest.raises(CustomException): - client.test_iam_permissions(resource, permissions) - def test_update_finding(self): # Setup Expected Response name = "name3373707" diff --git a/tests/unit/gapic/v1beta1/test_security_center_client_v1beta1.py b/tests/unit/gapic/v1beta1/test_security_center_client_v1beta1.py index 3cc4f388..bab98fc9 100644 --- a/tests/unit/gapic/v1beta1/test_security_center_client_v1beta1.py +++ b/tests/unit/gapic/v1beta1/test_security_center_client_v1beta1.py @@ -189,7 +189,7 @@ def test_get_iam_policy(self): client = securitycenter_v1beta1.SecurityCenterClient() # Setup Request - resource = "resource-341064690" + resource = client.source_path("[ORGANIZATION]", "[SOURCE]") response = client.get_iam_policy(resource) assert expected_response == response @@ -208,7 +208,7 @@ def test_get_iam_policy_exception(self): client = securitycenter_v1beta1.SecurityCenterClient() # Setup request - resource = "resource-341064690" + resource = client.source_path("[ORGANIZATION]", "[SOURCE]") with pytest.raises(CustomException): client.get_iam_policy(resource) @@ -673,7 +673,7 @@ def test_set_iam_policy(self): client = securitycenter_v1beta1.SecurityCenterClient() # Setup Request - resource = "resource-341064690" + resource = client.source_path("[ORGANIZATION]", "[SOURCE]") policy = {} response = client.set_iam_policy(resource, policy) @@ -695,7 +695,7 @@ def test_set_iam_policy_exception(self): client = securitycenter_v1beta1.SecurityCenterClient() # Setup request - resource = "resource-341064690" + resource = client.source_path("[ORGANIZATION]", "[SOURCE]") policy = {} with pytest.raises(CustomException): @@ -716,7 +716,7 @@ def test_test_iam_permissions(self): client = securitycenter_v1beta1.SecurityCenterClient() # Setup Request - resource = "resource-341064690" + resource = client.source_path("[ORGANIZATION]", "[SOURCE]") permissions = [] response = client.test_iam_permissions(resource, permissions) @@ -738,7 +738,7 @@ def test_test_iam_permissions_exception(self): client = securitycenter_v1beta1.SecurityCenterClient() # Setup request - resource = "resource-341064690" + resource = client.source_path("[ORGANIZATION]", "[SOURCE]") permissions = [] with pytest.raises(CustomException): From b1016cda274341cf81f94c42644ba84612f63aef Mon Sep 17 00:00:00 2001 From: yoshi-automation Date: Sat, 1 Aug 2020 11:24:14 -0700 Subject: [PATCH 07/17] Add/correct PHP namespace for BigQuery connection/reservation PiperOrigin-RevId: 323605868 Source-Author: Google APIs Source-Date: Tue Jul 28 10:47:24 2020 -0700 Source-Repo: googleapis/googleapis Source-Sha: 0c6a73081373ff3ff3d470efe554f2f1efd64041 Source-Link: https://github.com/googleapis/googleapis/commit/0c6a73081373ff3ff3d470efe554f2f1efd64041 --- .../services/security_center/async_client.py | 8 ++-- .../services/security_center/async_client.py | 4 +- .../services/security_center/async_client.py | 38 +++++++++---------- .../services/security_center/client.py | 22 +++++------ synth.metadata | 4 +- 5 files changed, 38 insertions(+), 38 deletions(-) diff --git a/google/cloud/securitycenter_v1/services/security_center/async_client.py b/google/cloud/securitycenter_v1/services/security_center/async_client.py index ea5a73ae..05a64296 100644 --- a/google/cloud/securitycenter_v1/services/security_center/async_client.py +++ b/google/cloud/securitycenter_v1/services/security_center/async_client.py @@ -66,18 +66,18 @@ class SecurityCenterAsyncClient: DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + source_path = staticmethod(SecurityCenterClient.source_path) + notification_config_path = staticmethod( SecurityCenterClient.notification_config_path ) - source_path = staticmethod(SecurityCenterClient.source_path) - - security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) - organization_settings_path = staticmethod( SecurityCenterClient.organization_settings_path ) + security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + finding_path = staticmethod(SecurityCenterClient.finding_path) from_service_account_file = SecurityCenterClient.from_service_account_file diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py b/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py index 2be877e7..4406edfe 100644 --- a/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py +++ b/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py @@ -66,11 +66,11 @@ class SecurityCenterAsyncClient: SecurityCenterClient.organization_settings_path ) - finding_path = staticmethod(SecurityCenterClient.finding_path) + security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) source_path = staticmethod(SecurityCenterClient.source_path) - security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + finding_path = staticmethod(SecurityCenterClient.finding_path) from_service_account_file = SecurityCenterClient.from_service_account_file from_service_account_json = from_service_account_file diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py index 4b652db0..dd1ab14d 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py @@ -68,20 +68,20 @@ class SecurityCenterAsyncClient: DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) - - organization_settings_path = staticmethod( - SecurityCenterClient.organization_settings_path - ) - - source_path = staticmethod(SecurityCenterClient.source_path) - notification_config_path = staticmethod( SecurityCenterClient.notification_config_path ) finding_path = staticmethod(SecurityCenterClient.finding_path) + security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + + source_path = staticmethod(SecurityCenterClient.source_path) + + organization_settings_path = staticmethod( + SecurityCenterClient.organization_settings_path + ) + from_service_account_file = SecurityCenterClient.from_service_account_file from_service_account_json = from_service_account_file @@ -614,7 +614,7 @@ async def get_iam_policy( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=60.0, @@ -699,7 +699,7 @@ async def get_notification_config( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=60.0, @@ -780,7 +780,7 @@ async def get_organization_settings( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=60.0, @@ -864,7 +864,7 @@ async def get_source( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=60.0, @@ -927,7 +927,7 @@ async def group_assets( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=480.0, @@ -1046,7 +1046,7 @@ async def group_findings( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=480.0, @@ -1132,7 +1132,7 @@ async def list_assets( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=480.0, @@ -1227,7 +1227,7 @@ async def list_findings( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=480.0, @@ -1316,7 +1316,7 @@ async def list_notification_configs( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=60.0, @@ -1403,7 +1403,7 @@ async def list_sources( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=60.0, @@ -1837,7 +1837,7 @@ async def test_iam_permissions( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=60.0, diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py index eddf3f24..9248651a 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py @@ -804,7 +804,7 @@ def get_iam_policy( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=60.0, @@ -889,7 +889,7 @@ def get_notification_config( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=60.0, @@ -970,7 +970,7 @@ def get_organization_settings( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=60.0, @@ -1054,7 +1054,7 @@ def get_source( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=60.0, @@ -1117,7 +1117,7 @@ def group_assets( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=480.0, @@ -1236,7 +1236,7 @@ def group_findings( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=480.0, @@ -1322,7 +1322,7 @@ def list_assets( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=480.0, @@ -1417,7 +1417,7 @@ def list_findings( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=480.0, @@ -1506,7 +1506,7 @@ def list_notification_configs( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=60.0, @@ -1593,7 +1593,7 @@ def list_sources( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=60.0, @@ -2027,7 +2027,7 @@ def test_iam_permissions( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=60.0, diff --git a/synth.metadata b/synth.metadata index 2c0b66bb..7d8b6da5 100644 --- a/synth.metadata +++ b/synth.metadata @@ -11,8 +11,8 @@ "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "6a813acf535e4746fa4a135ce23547bb6425c26d", - "internalRef": "323472217" + "sha": "0c6a73081373ff3ff3d470efe554f2f1efd64041", + "internalRef": "323605868" } }, { From c32c67bebaee7a5e1f96a0b6deef6ae803bc12e6 Mon Sep 17 00:00:00 2001 From: yoshi-automation Date: Sat, 1 Aug 2020 11:24:14 -0700 Subject: [PATCH 08/17] chore: upgrade to gapic-generator-python 0.30.0 PiperOrigin-RevId: 323630732 Source-Author: Google APIs Source-Date: Tue Jul 28 12:37:10 2020 -0700 Source-Repo: googleapis/googleapis Source-Sha: 74e8cf85f23d3cef04fcc75b4f59a21a2b41886c Source-Link: https://github.com/googleapis/googleapis/commit/74e8cf85f23d3cef04fcc75b4f59a21a2b41886c --- .../services/security_center/async_client.py | 12 +- .../services/security_center/client.py | 238 +++--------------- .../security_center/transports/base.py | 211 ++++++++++++++++ .../security_center/transports/grpc.py | 4 +- .../services/security_center/async_client.py | 8 +- .../services/security_center/client.py | 184 ++------------ .../security_center/transports/base.py | 170 +++++++++++++ .../security_center/transports/grpc.py | 4 +- .../services/security_center/async_client.py | 34 +-- .../services/security_center/client.py | 238 +++--------------- .../security_center/transports/base.py | 211 ++++++++++++++++ .../security_center/transports/grpc.py | 4 +- synth.metadata | 4 +- 13 files changed, 719 insertions(+), 603 deletions(-) diff --git a/google/cloud/securitycenter_v1/services/security_center/async_client.py b/google/cloud/securitycenter_v1/services/security_center/async_client.py index 05a64296..5b2d6523 100644 --- a/google/cloud/securitycenter_v1/services/security_center/async_client.py +++ b/google/cloud/securitycenter_v1/services/security_center/async_client.py @@ -66,19 +66,19 @@ class SecurityCenterAsyncClient: DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - source_path = staticmethod(SecurityCenterClient.source_path) - - notification_config_path = staticmethod( - SecurityCenterClient.notification_config_path - ) + finding_path = staticmethod(SecurityCenterClient.finding_path) organization_settings_path = staticmethod( SecurityCenterClient.organization_settings_path ) + source_path = staticmethod(SecurityCenterClient.source_path) + security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) - finding_path = staticmethod(SecurityCenterClient.finding_path) + notification_config_path = staticmethod( + SecurityCenterClient.notification_config_path + ) from_service_account_file = SecurityCenterClient.from_service_account_file from_service_account_json = from_service_account_file diff --git a/google/cloud/securitycenter_v1/services/security_center/client.py b/google/cloud/securitycenter_v1/services/security_center/client.py index c10e346c..5848c82f 100644 --- a/google/cloud/securitycenter_v1/services/security_center/client.py +++ b/google/cloud/securitycenter_v1/services/security_center/client.py @@ -385,11 +385,7 @@ def create_source( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.create_source, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.create_source] # Certain fields should be provided within the metadata header; # add these here. @@ -487,11 +483,7 @@ def create_finding( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.create_finding, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.create_finding] # Certain fields should be provided within the metadata header; # add these here. @@ -586,11 +578,9 @@ def create_notification_config( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.create_notification_config, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.create_notification_config + ] # Certain fields should be provided within the metadata header; # add these here. @@ -652,11 +642,9 @@ def delete_notification_config( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_notification_config, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.delete_notification_config + ] # Certain fields should be provided within the metadata header; # add these here. @@ -794,19 +782,7 @@ def get_iam_policy( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_iam_policy, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] # Certain fields should be provided within the metadata header; # add these here. @@ -878,19 +854,7 @@ def get_notification_config( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_notification_config, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.get_notification_config] # Certain fields should be provided within the metadata header; # add these here. @@ -959,19 +923,9 @@ def get_organization_settings( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_organization_settings, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.get_organization_settings + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1043,19 +997,7 @@ def get_source( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_source, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.get_source] # Certain fields should be provided within the metadata header; # add these here. @@ -1106,19 +1048,7 @@ def group_assets( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.group_assets, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.group_assets] # Certain fields should be provided within the metadata header; # add these here. @@ -1224,19 +1154,7 @@ def group_findings( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.group_findings, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.group_findings] # Certain fields should be provided within the metadata header; # add these here. @@ -1290,19 +1208,7 @@ def list_assets( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_assets, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.list_assets] # Certain fields should be provided within the metadata header; # add these here. @@ -1361,19 +1267,7 @@ def list_findings( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_findings, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.list_findings] # Certain fields should be provided within the metadata header; # add these here. @@ -1450,19 +1344,9 @@ def list_notification_configs( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_notification_configs, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.list_notification_configs + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1537,19 +1421,7 @@ def list_sources( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_sources, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.list_sources] # Certain fields should be provided within the metadata header; # add these here. @@ -1631,11 +1503,7 @@ def run_asset_discovery( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.run_asset_discovery, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.run_asset_discovery] # Certain fields should be provided within the metadata header; # add these here. @@ -1738,11 +1606,7 @@ def set_finding_state( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.set_finding_state, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.set_finding_state] # Certain fields should be provided within the metadata header; # add these here. @@ -1881,11 +1745,7 @@ def set_iam_policy( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.set_iam_policy, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] # Certain fields should be provided within the metadata header; # add these here. @@ -1971,19 +1831,7 @@ def test_iam_permissions( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.test_iam_permissions, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] # Certain fields should be provided within the metadata header; # add these here. @@ -2063,11 +1911,7 @@ def update_finding( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.update_finding, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.update_finding] # Certain fields should be provided within the metadata header; # add these here. @@ -2152,11 +1996,9 @@ def update_notification_config( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.update_notification_config, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.update_notification_config + ] # Certain fields should be provided within the metadata header; # add these here. @@ -2226,11 +2068,9 @@ def update_organization_settings( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.update_organization_settings, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.update_organization_settings + ] # Certain fields should be provided within the metadata header; # add these here. @@ -2303,11 +2143,7 @@ def update_source( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.update_source, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.update_source] # Certain fields should be provided within the metadata header; # add these here. @@ -2382,11 +2218,7 @@ def update_security_marks( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.update_security_marks, - default_timeout=480.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.update_security_marks] # Certain fields should be provided within the metadata header; # add these here. diff --git a/google/cloud/securitycenter_v1/services/security_center/transports/base.py b/google/cloud/securitycenter_v1/services/security_center/transports/base.py index 189a0d3b..c7e6232a 100644 --- a/google/cloud/securitycenter_v1/services/security_center/transports/base.py +++ b/google/cloud/securitycenter_v1/services/security_center/transports/base.py @@ -17,9 +17,11 @@ import abc import typing +import pkg_resources from google import auth from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore from google.api_core import operations_v1 # type: ignore from google.auth import credentials # type: ignore @@ -43,6 +45,16 @@ from google.protobuf import empty_pb2 as empty # type: ignore +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-securitycenter", + ).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + class SecurityCenterTransport(abc.ABC): """Abstract transport class for SecurityCenter.""" @@ -99,6 +111,205 @@ def __init__( # Save the credentials. self._credentials = credentials + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages() + + def _prep_wrapped_messages(self): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_source: gapic_v1.method.wrap_method( + self.create_source, default_timeout=60.0, client_info=_client_info, + ), + self.create_finding: gapic_v1.method.wrap_method( + self.create_finding, default_timeout=60.0, client_info=_client_info, + ), + self.create_notification_config: gapic_v1.method.wrap_method( + self.create_notification_config, + default_timeout=60.0, + client_info=_client_info, + ), + self.delete_notification_config: gapic_v1.method.wrap_method( + self.delete_notification_config, + default_timeout=60.0, + client_info=_client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.get_notification_config: gapic_v1.method.wrap_method( + self.get_notification_config, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.get_organization_settings: gapic_v1.method.wrap_method( + self.get_organization_settings, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.get_source: gapic_v1.method.wrap_method( + self.get_source, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.group_assets: gapic_v1.method.wrap_method( + self.group_assets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ), + self.group_findings: gapic_v1.method.wrap_method( + self.group_findings, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ), + self.list_assets: gapic_v1.method.wrap_method( + self.list_assets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ), + self.list_findings: gapic_v1.method.wrap_method( + self.list_findings, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ), + self.list_notification_configs: gapic_v1.method.wrap_method( + self.list_notification_configs, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.list_sources: gapic_v1.method.wrap_method( + self.list_sources, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.run_asset_discovery: gapic_v1.method.wrap_method( + self.run_asset_discovery, + default_timeout=60.0, + client_info=_client_info, + ), + self.set_finding_state: gapic_v1.method.wrap_method( + self.set_finding_state, default_timeout=60.0, client_info=_client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, default_timeout=60.0, client_info=_client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.update_finding: gapic_v1.method.wrap_method( + self.update_finding, default_timeout=60.0, client_info=_client_info, + ), + self.update_notification_config: gapic_v1.method.wrap_method( + self.update_notification_config, + default_timeout=60.0, + client_info=_client_info, + ), + self.update_organization_settings: gapic_v1.method.wrap_method( + self.update_organization_settings, + default_timeout=60.0, + client_info=_client_info, + ), + self.update_source: gapic_v1.method.wrap_method( + self.update_source, default_timeout=60.0, client_info=_client_info, + ), + self.update_security_marks: gapic_v1.method.wrap_method( + self.update_security_marks, + default_timeout=480.0, + client_info=_client_info, + ), + } + @property def operations_client(self) -> operations_v1.OperationsClient: """Return the client designed to process long-running operations.""" diff --git a/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py b/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py index c0900c9e..5e5e3b95 100644 --- a/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py +++ b/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py @@ -148,6 +148,8 @@ def __init__( quota_project_id=quota_project_id, ) + self._stubs = {} # type: Dict[str, Callable] + # Run the base constructor. super().__init__( host=host, @@ -157,8 +159,6 @@ def __init__( quota_project_id=quota_project_id, ) - self._stubs = {} # type: Dict[str, Callable] - @classmethod def create_channel( cls, diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py b/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py index 4406edfe..14631074 100644 --- a/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py +++ b/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py @@ -62,14 +62,14 @@ class SecurityCenterAsyncClient: DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - organization_settings_path = staticmethod( - SecurityCenterClient.organization_settings_path - ) - security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) source_path = staticmethod(SecurityCenterClient.source_path) + organization_settings_path = staticmethod( + SecurityCenterClient.organization_settings_path + ) + finding_path = staticmethod(SecurityCenterClient.finding_path) from_service_account_file = SecurityCenterClient.from_service_account_file diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/client.py b/google/cloud/securitycenter_v1beta1/services/security_center/client.py index 5e82612a..1c9cabce 100644 --- a/google/cloud/securitycenter_v1beta1/services/security_center/client.py +++ b/google/cloud/securitycenter_v1beta1/services/security_center/client.py @@ -365,11 +365,7 @@ def create_source( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.create_source, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.create_source] # Certain fields should be provided within the metadata header; # add these here. @@ -467,11 +463,7 @@ def create_finding( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.create_finding, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.create_finding] # Certain fields should be provided within the metadata header; # add these here. @@ -610,19 +602,7 @@ def get_iam_policy( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_iam_policy, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] # Certain fields should be provided within the metadata header; # add these here. @@ -691,19 +671,9 @@ def get_organization_settings( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_organization_settings, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.get_organization_settings + ] # Certain fields should be provided within the metadata header; # add these here. @@ -775,19 +745,7 @@ def get_source( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_source, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.get_source] # Certain fields should be provided within the metadata header; # add these here. @@ -838,19 +796,7 @@ def group_assets( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.group_assets, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.group_assets] # Certain fields should be provided within the metadata header; # add these here. @@ -952,19 +898,7 @@ def group_findings( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.group_findings, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.group_findings] # Certain fields should be provided within the metadata header; # add these here. @@ -1018,19 +952,7 @@ def list_assets( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_assets, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.list_assets] # Certain fields should be provided within the metadata header; # add these here. @@ -1090,19 +1012,7 @@ def list_findings( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_findings, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.list_findings] # Certain fields should be provided within the metadata header; # add these here. @@ -1177,19 +1087,7 @@ def list_sources( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_sources, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.list_sources] # Certain fields should be provided within the metadata header; # add these here. @@ -1283,11 +1181,7 @@ def run_asset_discovery( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.run_asset_discovery, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.run_asset_discovery] # Certain fields should be provided within the metadata header; # add these here. @@ -1390,11 +1284,7 @@ def set_finding_state( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.set_finding_state, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.set_finding_state] # Certain fields should be provided within the metadata header; # add these here. @@ -1533,11 +1423,7 @@ def set_iam_policy( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.set_iam_policy, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] # Certain fields should be provided within the metadata header; # add these here. @@ -1623,19 +1509,7 @@ def test_iam_permissions( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.test_iam_permissions, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] # Certain fields should be provided within the metadata header; # add these here. @@ -1715,11 +1589,7 @@ def update_finding( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.update_finding, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.update_finding] # Certain fields should be provided within the metadata header; # add these here. @@ -1789,11 +1659,9 @@ def update_organization_settings( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.update_organization_settings, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.update_organization_settings + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1866,11 +1734,7 @@ def update_source( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.update_source, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.update_source] # Certain fields should be provided within the metadata header; # add these here. @@ -1945,11 +1809,7 @@ def update_security_marks( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.update_security_marks, - default_timeout=480.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.update_security_marks] # Certain fields should be provided within the metadata header; # add these here. diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py b/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py index 0729c7d6..64aa9985 100644 --- a/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py +++ b/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py @@ -17,9 +17,11 @@ import abc import typing +import pkg_resources from google import auth from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore from google.api_core import operations_v1 # type: ignore from google.auth import credentials # type: ignore @@ -40,6 +42,16 @@ from google.longrunning import operations_pb2 as operations # type: ignore +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-securitycenter", + ).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + class SecurityCenterTransport(abc.ABC): """Abstract transport class for SecurityCenter.""" @@ -96,6 +108,164 @@ def __init__( # Save the credentials. self._credentials = credentials + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages() + + def _prep_wrapped_messages(self): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_source: gapic_v1.method.wrap_method( + self.create_source, default_timeout=60.0, client_info=_client_info, + ), + self.create_finding: gapic_v1.method.wrap_method( + self.create_finding, default_timeout=60.0, client_info=_client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.get_organization_settings: gapic_v1.method.wrap_method( + self.get_organization_settings, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.get_source: gapic_v1.method.wrap_method( + self.get_source, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.group_assets: gapic_v1.method.wrap_method( + self.group_assets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ), + self.group_findings: gapic_v1.method.wrap_method( + self.group_findings, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ), + self.list_assets: gapic_v1.method.wrap_method( + self.list_assets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ), + self.list_findings: gapic_v1.method.wrap_method( + self.list_findings, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ), + self.list_sources: gapic_v1.method.wrap_method( + self.list_sources, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.run_asset_discovery: gapic_v1.method.wrap_method( + self.run_asset_discovery, + default_timeout=60.0, + client_info=_client_info, + ), + self.set_finding_state: gapic_v1.method.wrap_method( + self.set_finding_state, default_timeout=60.0, client_info=_client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, default_timeout=60.0, client_info=_client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.update_finding: gapic_v1.method.wrap_method( + self.update_finding, default_timeout=60.0, client_info=_client_info, + ), + self.update_organization_settings: gapic_v1.method.wrap_method( + self.update_organization_settings, + default_timeout=60.0, + client_info=_client_info, + ), + self.update_source: gapic_v1.method.wrap_method( + self.update_source, default_timeout=60.0, client_info=_client_info, + ), + self.update_security_marks: gapic_v1.method.wrap_method( + self.update_security_marks, + default_timeout=480.0, + client_info=_client_info, + ), + } + @property def operations_client(self) -> operations_v1.OperationsClient: """Return the client designed to process long-running operations.""" diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py b/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py index 45296ba3..37b8b413 100644 --- a/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py +++ b/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py @@ -145,6 +145,8 @@ def __init__( quota_project_id=quota_project_id, ) + self._stubs = {} # type: Dict[str, Callable] + # Run the base constructor. super().__init__( host=host, @@ -154,8 +156,6 @@ def __init__( quota_project_id=quota_project_id, ) - self._stubs = {} # type: Dict[str, Callable] - @classmethod def create_channel( cls, diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py index dd1ab14d..52ca15ac 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py @@ -68,20 +68,20 @@ class SecurityCenterAsyncClient: DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - notification_config_path = staticmethod( - SecurityCenterClient.notification_config_path - ) - - finding_path = staticmethod(SecurityCenterClient.finding_path) + source_path = staticmethod(SecurityCenterClient.source_path) security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) - source_path = staticmethod(SecurityCenterClient.source_path) + finding_path = staticmethod(SecurityCenterClient.finding_path) organization_settings_path = staticmethod( SecurityCenterClient.organization_settings_path ) + notification_config_path = staticmethod( + SecurityCenterClient.notification_config_path + ) + from_service_account_file = SecurityCenterClient.from_service_account_file from_service_account_json = from_service_account_file @@ -614,7 +614,7 @@ async def get_iam_policy( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=60.0, @@ -699,7 +699,7 @@ async def get_notification_config( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=60.0, @@ -780,7 +780,7 @@ async def get_organization_settings( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=60.0, @@ -864,7 +864,7 @@ async def get_source( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=60.0, @@ -927,7 +927,7 @@ async def group_assets( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=480.0, @@ -1046,7 +1046,7 @@ async def group_findings( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=480.0, @@ -1132,7 +1132,7 @@ async def list_assets( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=480.0, @@ -1227,7 +1227,7 @@ async def list_findings( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=480.0, @@ -1316,7 +1316,7 @@ async def list_notification_configs( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=60.0, @@ -1403,7 +1403,7 @@ async def list_sources( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=60.0, @@ -1837,7 +1837,7 @@ async def test_iam_permissions( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=60.0, diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py index 9248651a..bdca86ae 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py @@ -387,11 +387,7 @@ def create_source( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.create_source, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.create_source] # Certain fields should be provided within the metadata header; # add these here. @@ -489,11 +485,7 @@ def create_finding( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.create_finding, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.create_finding] # Certain fields should be provided within the metadata header; # add these here. @@ -589,11 +581,9 @@ def create_notification_config( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.create_notification_config, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.create_notification_config + ] # Certain fields should be provided within the metadata header; # add these here. @@ -655,11 +645,9 @@ def delete_notification_config( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.delete_notification_config, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.delete_notification_config + ] # Certain fields should be provided within the metadata header; # add these here. @@ -797,19 +785,7 @@ def get_iam_policy( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_iam_policy, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] # Certain fields should be provided within the metadata header; # add these here. @@ -882,19 +858,7 @@ def get_notification_config( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_notification_config, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.get_notification_config] # Certain fields should be provided within the metadata header; # add these here. @@ -963,19 +927,9 @@ def get_organization_settings( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_organization_settings, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.get_organization_settings + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1047,19 +1001,7 @@ def get_source( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.get_source, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.get_source] # Certain fields should be provided within the metadata header; # add these here. @@ -1110,19 +1052,7 @@ def group_assets( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.group_assets, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.group_assets] # Certain fields should be provided within the metadata header; # add these here. @@ -1229,19 +1159,7 @@ def group_findings( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.group_findings, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.group_findings] # Certain fields should be provided within the metadata header; # add these here. @@ -1315,19 +1233,7 @@ def list_assets( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_assets, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.list_assets] # Certain fields should be provided within the metadata header; # add these here. @@ -1410,19 +1316,7 @@ def list_findings( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_findings, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.list_findings] # Certain fields should be provided within the metadata header; # add these here. @@ -1499,19 +1393,9 @@ def list_notification_configs( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_notification_configs, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.list_notification_configs + ] # Certain fields should be provided within the metadata header; # add these here. @@ -1586,19 +1470,7 @@ def list_sources( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.list_sources, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.list_sources] # Certain fields should be provided within the metadata header; # add these here. @@ -1680,11 +1552,7 @@ def run_asset_discovery( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.run_asset_discovery, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.run_asset_discovery] # Certain fields should be provided within the metadata header; # add these here. @@ -1787,11 +1655,7 @@ def set_finding_state( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.set_finding_state, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.set_finding_state] # Certain fields should be provided within the metadata header; # add these here. @@ -1930,11 +1794,7 @@ def set_iam_policy( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.set_iam_policy, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] # Certain fields should be provided within the metadata header; # add these here. @@ -2020,19 +1880,7 @@ def test_iam_permissions( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.test_iam_permissions, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] # Certain fields should be provided within the metadata header; # add these here. @@ -2128,11 +1976,7 @@ def update_finding( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.update_finding, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.update_finding] # Certain fields should be provided within the metadata header; # add these here. @@ -2218,11 +2062,9 @@ def update_notification_config( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.update_notification_config, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.update_notification_config + ] # Certain fields should be provided within the metadata header; # add these here. @@ -2292,11 +2134,9 @@ def update_organization_settings( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.update_organization_settings, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[ + self._transport.update_organization_settings + ] # Certain fields should be provided within the metadata header; # add these here. @@ -2380,11 +2220,7 @@ def update_source( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.update_source, - default_timeout=60.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.update_source] # Certain fields should be provided within the metadata header; # add these here. @@ -2473,11 +2309,7 @@ def update_security_marks( # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. - rpc = gapic_v1.method.wrap_method( - self._transport.update_security_marks, - default_timeout=480.0, - client_info=_client_info, - ) + rpc = self._transport._wrapped_methods[self._transport.update_security_marks] # Certain fields should be provided within the metadata header; # add these here. diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py index ddb8520d..47b6ac39 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py @@ -17,9 +17,11 @@ import abc import typing +import pkg_resources from google import auth from google.api_core import exceptions # type: ignore +from google.api_core import gapic_v1 # type: ignore from google.api_core import operations_v1 # type: ignore from google.auth import credentials # type: ignore @@ -45,6 +47,16 @@ from google.protobuf import empty_pb2 as empty # type: ignore +try: + _client_info = gapic_v1.client_info.ClientInfo( + gapic_version=pkg_resources.get_distribution( + "google-cloud-securitycenter", + ).version, + ) +except pkg_resources.DistributionNotFound: + _client_info = gapic_v1.client_info.ClientInfo() + + class SecurityCenterTransport(abc.ABC): """Abstract transport class for SecurityCenter.""" @@ -101,6 +113,205 @@ def __init__( # Save the credentials. self._credentials = credentials + # Lifted into its own function so it can be stubbed out during tests. + self._prep_wrapped_messages() + + def _prep_wrapped_messages(self): + # Precompute the wrapped methods. + self._wrapped_methods = { + self.create_source: gapic_v1.method.wrap_method( + self.create_source, default_timeout=60.0, client_info=_client_info, + ), + self.create_finding: gapic_v1.method.wrap_method( + self.create_finding, default_timeout=60.0, client_info=_client_info, + ), + self.create_notification_config: gapic_v1.method.wrap_method( + self.create_notification_config, + default_timeout=60.0, + client_info=_client_info, + ), + self.delete_notification_config: gapic_v1.method.wrap_method( + self.delete_notification_config, + default_timeout=60.0, + client_info=_client_info, + ), + self.get_iam_policy: gapic_v1.method.wrap_method( + self.get_iam_policy, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.get_notification_config: gapic_v1.method.wrap_method( + self.get_notification_config, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.get_organization_settings: gapic_v1.method.wrap_method( + self.get_organization_settings, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.get_source: gapic_v1.method.wrap_method( + self.get_source, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.group_assets: gapic_v1.method.wrap_method( + self.group_assets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ), + self.group_findings: gapic_v1.method.wrap_method( + self.group_findings, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ), + self.list_assets: gapic_v1.method.wrap_method( + self.list_assets, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ), + self.list_findings: gapic_v1.method.wrap_method( + self.list_findings, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=480.0, + client_info=_client_info, + ), + self.list_notification_configs: gapic_v1.method.wrap_method( + self.list_notification_configs, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.list_sources: gapic_v1.method.wrap_method( + self.list_sources, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.run_asset_discovery: gapic_v1.method.wrap_method( + self.run_asset_discovery, + default_timeout=60.0, + client_info=_client_info, + ), + self.set_finding_state: gapic_v1.method.wrap_method( + self.set_finding_state, default_timeout=60.0, client_info=_client_info, + ), + self.set_iam_policy: gapic_v1.method.wrap_method( + self.set_iam_policy, default_timeout=60.0, client_info=_client_info, + ), + self.test_iam_permissions: gapic_v1.method.wrap_method( + self.test_iam_permissions, + default_retry=retries.Retry( + initial=0.1, + maximum=60.0, + multiplier=1.3, + predicate=retries.if_exception_type( + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + ), + ), + default_timeout=60.0, + client_info=_client_info, + ), + self.update_finding: gapic_v1.method.wrap_method( + self.update_finding, default_timeout=60.0, client_info=_client_info, + ), + self.update_notification_config: gapic_v1.method.wrap_method( + self.update_notification_config, + default_timeout=60.0, + client_info=_client_info, + ), + self.update_organization_settings: gapic_v1.method.wrap_method( + self.update_organization_settings, + default_timeout=60.0, + client_info=_client_info, + ), + self.update_source: gapic_v1.method.wrap_method( + self.update_source, default_timeout=60.0, client_info=_client_info, + ), + self.update_security_marks: gapic_v1.method.wrap_method( + self.update_security_marks, + default_timeout=480.0, + client_info=_client_info, + ), + } + @property def operations_client(self) -> operations_v1.OperationsClient: """Return the client designed to process long-running operations.""" diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py index e4d1f0e1..b1169fde 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py @@ -150,6 +150,8 @@ def __init__( quota_project_id=quota_project_id, ) + self._stubs = {} # type: Dict[str, Callable] + # Run the base constructor. super().__init__( host=host, @@ -159,8 +161,6 @@ def __init__( quota_project_id=quota_project_id, ) - self._stubs = {} # type: Dict[str, Callable] - @classmethod def create_channel( cls, diff --git a/synth.metadata b/synth.metadata index 7d8b6da5..4b644061 100644 --- a/synth.metadata +++ b/synth.metadata @@ -11,8 +11,8 @@ "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "0c6a73081373ff3ff3d470efe554f2f1efd64041", - "internalRef": "323605868" + "sha": "74e8cf85f23d3cef04fcc75b4f59a21a2b41886c", + "internalRef": "323630732" } }, { From f0c1a58442cc22f47de56a3d16ce2d67735836b8 Mon Sep 17 00:00:00 2001 From: yoshi-automation Date: Sat, 1 Aug 2020 11:24:44 -0700 Subject: [PATCH 09/17] feat: Add Dataproc Metastore v1alpha API. PiperOrigin-RevId: 323657371 Source-Author: Google APIs Source-Date: Tue Jul 28 14:43:58 2020 -0700 Source-Repo: googleapis/googleapis Source-Sha: 1907f0fdbd1c51e62d8452a4007bf2134a8bd4c2 Source-Link: https://github.com/googleapis/googleapis/commit/1907f0fdbd1c51e62d8452a4007bf2134a8bd4c2 --- .../services/security_center/async_client.py | 32 +++++++++---------- .../security_center/transports/base.py | 22 ++++++------- .../services/security_center/async_client.py | 8 ++--- .../services/security_center/async_client.py | 10 +++--- synth.metadata | 4 +-- 5 files changed, 38 insertions(+), 38 deletions(-) diff --git a/google/cloud/securitycenter_v1/services/security_center/async_client.py b/google/cloud/securitycenter_v1/services/security_center/async_client.py index 5b2d6523..1f7ace7b 100644 --- a/google/cloud/securitycenter_v1/services/security_center/async_client.py +++ b/google/cloud/securitycenter_v1/services/security_center/async_client.py @@ -66,19 +66,19 @@ class SecurityCenterAsyncClient: DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - finding_path = staticmethod(SecurityCenterClient.finding_path) + notification_config_path = staticmethod( + SecurityCenterClient.notification_config_path + ) organization_settings_path = staticmethod( SecurityCenterClient.organization_settings_path ) - source_path = staticmethod(SecurityCenterClient.source_path) + finding_path = staticmethod(SecurityCenterClient.finding_path) security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) - notification_config_path = staticmethod( - SecurityCenterClient.notification_config_path - ) + source_path = staticmethod(SecurityCenterClient.source_path) from_service_account_file = SecurityCenterClient.from_service_account_file from_service_account_json = from_service_account_file @@ -611,7 +611,7 @@ async def get_iam_policy( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=60.0, @@ -695,7 +695,7 @@ async def get_notification_config( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=60.0, @@ -776,7 +776,7 @@ async def get_organization_settings( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=60.0, @@ -860,7 +860,7 @@ async def get_source( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=60.0, @@ -923,7 +923,7 @@ async def group_assets( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=480.0, @@ -1041,7 +1041,7 @@ async def group_findings( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=480.0, @@ -1107,7 +1107,7 @@ async def list_assets( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=480.0, @@ -1178,7 +1178,7 @@ async def list_findings( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=480.0, @@ -1267,7 +1267,7 @@ async def list_notification_configs( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=60.0, @@ -1354,7 +1354,7 @@ async def list_sources( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=60.0, @@ -1788,7 +1788,7 @@ async def test_iam_permissions( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=60.0, diff --git a/google/cloud/securitycenter_v1/services/security_center/transports/base.py b/google/cloud/securitycenter_v1/services/security_center/transports/base.py index c7e6232a..d606ce76 100644 --- a/google/cloud/securitycenter_v1/services/security_center/transports/base.py +++ b/google/cloud/securitycenter_v1/services/security_center/transports/base.py @@ -140,7 +140,7 @@ def _prep_wrapped_messages(self): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=60.0, @@ -153,7 +153,7 @@ def _prep_wrapped_messages(self): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=60.0, @@ -166,7 +166,7 @@ def _prep_wrapped_messages(self): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=60.0, @@ -179,7 +179,7 @@ def _prep_wrapped_messages(self): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=60.0, @@ -192,7 +192,7 @@ def _prep_wrapped_messages(self): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=480.0, @@ -205,7 +205,7 @@ def _prep_wrapped_messages(self): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=480.0, @@ -218,7 +218,7 @@ def _prep_wrapped_messages(self): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=480.0, @@ -231,7 +231,7 @@ def _prep_wrapped_messages(self): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=480.0, @@ -244,7 +244,7 @@ def _prep_wrapped_messages(self): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=60.0, @@ -257,7 +257,7 @@ def _prep_wrapped_messages(self): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=60.0, @@ -281,7 +281,7 @@ def _prep_wrapped_messages(self): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, + exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, ), ), default_timeout=60.0, diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py b/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py index 14631074..2ddb1751 100644 --- a/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py +++ b/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py @@ -62,16 +62,16 @@ class SecurityCenterAsyncClient: DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) - - source_path = staticmethod(SecurityCenterClient.source_path) - organization_settings_path = staticmethod( SecurityCenterClient.organization_settings_path ) + security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + finding_path = staticmethod(SecurityCenterClient.finding_path) + source_path = staticmethod(SecurityCenterClient.source_path) + from_service_account_file = SecurityCenterClient.from_service_account_file from_service_account_json = from_service_account_file diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py index 52ca15ac..06704255 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py @@ -68,19 +68,19 @@ class SecurityCenterAsyncClient: DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - source_path = staticmethod(SecurityCenterClient.source_path) + finding_path = staticmethod(SecurityCenterClient.finding_path) security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) - finding_path = staticmethod(SecurityCenterClient.finding_path) + notification_config_path = staticmethod( + SecurityCenterClient.notification_config_path + ) organization_settings_path = staticmethod( SecurityCenterClient.organization_settings_path ) - notification_config_path = staticmethod( - SecurityCenterClient.notification_config_path - ) + source_path = staticmethod(SecurityCenterClient.source_path) from_service_account_file = SecurityCenterClient.from_service_account_file from_service_account_json = from_service_account_file diff --git a/synth.metadata b/synth.metadata index 4b644061..810e6654 100644 --- a/synth.metadata +++ b/synth.metadata @@ -11,8 +11,8 @@ "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "74e8cf85f23d3cef04fcc75b4f59a21a2b41886c", - "internalRef": "323630732" + "sha": "1907f0fdbd1c51e62d8452a4007bf2134a8bd4c2", + "internalRef": "323657371" } }, { From 6e65b88c9cf357d61f242be6f52ed8b0f974407d Mon Sep 17 00:00:00 2001 From: yoshi-automation Date: Sat, 1 Aug 2020 11:24:57 -0700 Subject: [PATCH 10/17] Correct PHP namespace for BigQuery connection PiperOrigin-RevId: 323795963 Source-Author: Google APIs Source-Date: Wed Jul 29 08:50:52 2020 -0700 Source-Repo: googleapis/googleapis Source-Sha: c1b9289be1be876ef494f31c9662bc49b4f906e0 Source-Link: https://github.com/googleapis/googleapis/commit/c1b9289be1be876ef494f31c9662bc49b4f906e0 --- .../services/security_center/async_client.py | 8 ++++---- .../services/security_center/async_client.py | 8 ++++---- .../services/security_center/async_client.py | 4 ++-- synth.metadata | 4 ++-- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/google/cloud/securitycenter_v1/services/security_center/async_client.py b/google/cloud/securitycenter_v1/services/security_center/async_client.py index 1f7ace7b..c1f054a7 100644 --- a/google/cloud/securitycenter_v1/services/security_center/async_client.py +++ b/google/cloud/securitycenter_v1/services/security_center/async_client.py @@ -66,20 +66,20 @@ class SecurityCenterAsyncClient: DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + finding_path = staticmethod(SecurityCenterClient.finding_path) + notification_config_path = staticmethod( SecurityCenterClient.notification_config_path ) + source_path = staticmethod(SecurityCenterClient.source_path) + organization_settings_path = staticmethod( SecurityCenterClient.organization_settings_path ) - finding_path = staticmethod(SecurityCenterClient.finding_path) - security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) - source_path = staticmethod(SecurityCenterClient.source_path) - from_service_account_file = SecurityCenterClient.from_service_account_file from_service_account_json = from_service_account_file diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py b/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py index 2ddb1751..1b410e1d 100644 --- a/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py +++ b/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py @@ -62,15 +62,15 @@ class SecurityCenterAsyncClient: DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - organization_settings_path = staticmethod( - SecurityCenterClient.organization_settings_path - ) + source_path = staticmethod(SecurityCenterClient.source_path) security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) finding_path = staticmethod(SecurityCenterClient.finding_path) - source_path = staticmethod(SecurityCenterClient.source_path) + organization_settings_path = staticmethod( + SecurityCenterClient.organization_settings_path + ) from_service_account_file = SecurityCenterClient.from_service_account_file from_service_account_json = from_service_account_file diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py index 06704255..cce63f61 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py @@ -70,7 +70,7 @@ class SecurityCenterAsyncClient: finding_path = staticmethod(SecurityCenterClient.finding_path) - security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + source_path = staticmethod(SecurityCenterClient.source_path) notification_config_path = staticmethod( SecurityCenterClient.notification_config_path @@ -80,7 +80,7 @@ class SecurityCenterAsyncClient: SecurityCenterClient.organization_settings_path ) - source_path = staticmethod(SecurityCenterClient.source_path) + security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) from_service_account_file = SecurityCenterClient.from_service_account_file from_service_account_json = from_service_account_file diff --git a/synth.metadata b/synth.metadata index 810e6654..fb6ae1c3 100644 --- a/synth.metadata +++ b/synth.metadata @@ -11,8 +11,8 @@ "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "1907f0fdbd1c51e62d8452a4007bf2134a8bd4c2", - "internalRef": "323657371" + "sha": "c1b9289be1be876ef494f31c9662bc49b4f906e0", + "internalRef": "323795963" } }, { From edd6e0eba554ff21ffd97ae6146798433481e003 Mon Sep 17 00:00:00 2001 From: yoshi-automation Date: Sat, 1 Aug 2020 11:25:39 -0700 Subject: [PATCH 11/17] Remove experimental warning for ordering keys properties. PiperOrigin-RevId: 323803770 Source-Author: Google APIs Source-Date: Wed Jul 29 09:31:38 2020 -0700 Source-Repo: googleapis/googleapis Source-Sha: 706053bbfb3f16ef752e513c2898a1f26cdd8e41 Source-Link: https://github.com/googleapis/googleapis/commit/706053bbfb3f16ef752e513c2898a1f26cdd8e41 --- .../services/security_center/async_client.py | 8 ++++---- .../services/security_center/async_client.py | 8 ++++---- .../services/security_center/async_client.py | 4 ++-- synth.metadata | 4 ++-- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/google/cloud/securitycenter_v1/services/security_center/async_client.py b/google/cloud/securitycenter_v1/services/security_center/async_client.py index c1f054a7..1f7ace7b 100644 --- a/google/cloud/securitycenter_v1/services/security_center/async_client.py +++ b/google/cloud/securitycenter_v1/services/security_center/async_client.py @@ -66,20 +66,20 @@ class SecurityCenterAsyncClient: DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - finding_path = staticmethod(SecurityCenterClient.finding_path) - notification_config_path = staticmethod( SecurityCenterClient.notification_config_path ) - source_path = staticmethod(SecurityCenterClient.source_path) - organization_settings_path = staticmethod( SecurityCenterClient.organization_settings_path ) + finding_path = staticmethod(SecurityCenterClient.finding_path) + security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + source_path = staticmethod(SecurityCenterClient.source_path) + from_service_account_file = SecurityCenterClient.from_service_account_file from_service_account_json = from_service_account_file diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py b/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py index 1b410e1d..2ddb1751 100644 --- a/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py +++ b/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py @@ -62,15 +62,15 @@ class SecurityCenterAsyncClient: DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - source_path = staticmethod(SecurityCenterClient.source_path) + organization_settings_path = staticmethod( + SecurityCenterClient.organization_settings_path + ) security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) finding_path = staticmethod(SecurityCenterClient.finding_path) - organization_settings_path = staticmethod( - SecurityCenterClient.organization_settings_path - ) + source_path = staticmethod(SecurityCenterClient.source_path) from_service_account_file = SecurityCenterClient.from_service_account_file from_service_account_json = from_service_account_file diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py index cce63f61..06704255 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py @@ -70,7 +70,7 @@ class SecurityCenterAsyncClient: finding_path = staticmethod(SecurityCenterClient.finding_path) - source_path = staticmethod(SecurityCenterClient.source_path) + security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) notification_config_path = staticmethod( SecurityCenterClient.notification_config_path @@ -80,7 +80,7 @@ class SecurityCenterAsyncClient: SecurityCenterClient.organization_settings_path ) - security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + source_path = staticmethod(SecurityCenterClient.source_path) from_service_account_file = SecurityCenterClient.from_service_account_file from_service_account_json = from_service_account_file diff --git a/synth.metadata b/synth.metadata index fb6ae1c3..ca9b7239 100644 --- a/synth.metadata +++ b/synth.metadata @@ -11,8 +11,8 @@ "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "c1b9289be1be876ef494f31c9662bc49b4f906e0", - "internalRef": "323795963" + "sha": "706053bbfb3f16ef752e513c2898a1f26cdd8e41", + "internalRef": "323803770" } }, { From bbc7f7faf6e7a40bcc98bb1c8cfb8f1c23df3040 Mon Sep 17 00:00:00 2001 From: yoshi-automation Date: Sat, 1 Aug 2020 11:26:29 -0700 Subject: [PATCH 12/17] update python micro-gen version PiperOrigin-RevId: 324035013 Source-Author: Google APIs Source-Date: Thu Jul 30 10:46:03 2020 -0700 Source-Repo: googleapis/googleapis Source-Sha: 8cda089accaead072caea33c5081be8a4b8f9ea7 Source-Link: https://github.com/googleapis/googleapis/commit/8cda089accaead072caea33c5081be8a4b8f9ea7 --- .../services/security_center/async_client.py | 8 +- .../services/security_center/client.py | 416 ++++++++++------ .../security_center/transports/base.py | 1 + .../services/security_center/async_client.py | 8 +- .../services/security_center/client.py | 302 ++++++++---- .../security_center/transports/base.py | 1 + .../services/security_center/async_client.py | 6 +- .../services/security_center/client.py | 450 ++++++++++++------ .../security_center/transports/base.py | 1 + synth.metadata | 4 +- 10 files changed, 780 insertions(+), 417 deletions(-) diff --git a/google/cloud/securitycenter_v1/services/security_center/async_client.py b/google/cloud/securitycenter_v1/services/security_center/async_client.py index 1f7ace7b..658ab5b0 100644 --- a/google/cloud/securitycenter_v1/services/security_center/async_client.py +++ b/google/cloud/securitycenter_v1/services/security_center/async_client.py @@ -66,6 +66,10 @@ class SecurityCenterAsyncClient: DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + finding_path = staticmethod(SecurityCenterClient.finding_path) + + security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + notification_config_path = staticmethod( SecurityCenterClient.notification_config_path ) @@ -74,10 +78,6 @@ class SecurityCenterAsyncClient: SecurityCenterClient.organization_settings_path ) - finding_path = staticmethod(SecurityCenterClient.finding_path) - - security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) - source_path = staticmethod(SecurityCenterClient.source_path) from_service_account_file = SecurityCenterClient.from_service_account_file diff --git a/google/cloud/securitycenter_v1/services/security_center/client.py b/google/cloud/securitycenter_v1/services/security_center/client.py index 5848c82f..d88ae32e 100644 --- a/google/cloud/securitycenter_v1/services/security_center/client.py +++ b/google/cloud/securitycenter_v1/services/security_center/client.py @@ -367,21 +367,27 @@ def create_source( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent, source]): + has_flattened_params = any([parent, source]) + 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." ) - request = securitycenter_service.CreateSourceRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.CreateSourceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.CreateSourceRequest): + request = securitycenter_service.CreateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent - if source is not None: - request.source = source + if parent is not None: + request.parent = parent + if source is not None: + request.source = source # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -463,23 +469,29 @@ def create_finding( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent, finding_id, finding]): + has_flattened_params = any([parent, finding_id, finding]) + 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." ) - request = securitycenter_service.CreateFindingRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.CreateFindingRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.CreateFindingRequest): + request = securitycenter_service.CreateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent - if finding_id is not None: - request.finding_id = finding_id - if finding is not None: - request.finding = finding + if parent is not None: + request.parent = parent + if finding_id is not None: + request.finding_id = finding_id + if finding is not None: + request.finding = finding # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -558,23 +570,31 @@ def create_notification_config( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent, config_id, notification_config]): + has_flattened_params = any([parent, config_id, notification_config]) + 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." ) - request = securitycenter_service.CreateNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if config_id is not None: - request.config_id = config_id - if notification_config is not None: - request.notification_config = notification_config + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.CreateNotificationConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, securitycenter_service.CreateNotificationConfigRequest + ): + request = securitycenter_service.CreateNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if config_id is not None: + request.config_id = config_id + if notification_config is not None: + request.notification_config = notification_config # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -626,19 +646,27 @@ def delete_notification_config( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + 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." ) - request = securitycenter_service.DeleteNotificationConfigRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.DeleteNotificationConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, securitycenter_service.DeleteNotificationConfigRequest + ): + request = securitycenter_service.DeleteNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -760,7 +788,8 @@ def get_iam_policy( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([resource]): + has_flattened_params = any([resource]) + 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." @@ -774,11 +803,11 @@ def get_iam_policy( elif not request: request = iam_policy.GetIamPolicyRequest() - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if resource is not None: - request.resource = resource + if resource is not None: + request.resource = resource # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -838,19 +867,25 @@ def get_notification_config( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + 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." ) - request = securitycenter_service.GetNotificationConfigRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GetNotificationConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): + request = securitycenter_service.GetNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -907,19 +942,27 @@ def get_organization_settings( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + 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." ) - request = securitycenter_service.GetOrganizationSettingsRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GetOrganizationSettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, securitycenter_service.GetOrganizationSettingsRequest + ): + request = securitycenter_service.GetOrganizationSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -981,19 +1024,25 @@ def get_source( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + 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." ) - request = securitycenter_service.GetSourceRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GetSourceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GetSourceRequest): + request = securitycenter_service.GetSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1044,7 +1093,12 @@ def group_assets( """ # Create or coerce a protobuf request object. - request = securitycenter_service.GroupAssetsRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GroupAssetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GroupAssetsRequest): + request = securitycenter_service.GroupAssetsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1136,21 +1190,27 @@ def group_findings( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent, group_by]): + has_flattened_params = any([parent, group_by]) + 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." ) - request = securitycenter_service.GroupFindingsRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GroupFindingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GroupFindingsRequest): + request = securitycenter_service.GroupFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1204,7 +1264,12 @@ def list_assets( """ # Create or coerce a protobuf request object. - request = securitycenter_service.ListAssetsRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListAssetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.ListAssetsRequest): + request = securitycenter_service.ListAssetsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1263,7 +1328,12 @@ def list_findings( """ # Create or coerce a protobuf request object. - request = securitycenter_service.ListFindingsRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListFindingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.ListFindingsRequest): + request = securitycenter_service.ListFindingsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1328,19 +1398,27 @@ def list_notification_configs( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): + has_flattened_params = any([parent]) + 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." ) - request = securitycenter_service.ListNotificationConfigsRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListNotificationConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, securitycenter_service.ListNotificationConfigsRequest + ): + request = securitycenter_service.ListNotificationConfigsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent + if parent is not None: + request.parent = parent # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1405,19 +1483,25 @@ def list_sources( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): + has_flattened_params = any([parent]) + 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." ) - request = securitycenter_service.ListSourcesRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListSourcesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.ListSourcesRequest): + request = securitycenter_service.ListSourcesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent + if parent is not None: + request.parent = parent # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1487,19 +1571,25 @@ def run_asset_discovery( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): + has_flattened_params = any([parent]) + 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." ) - request = securitycenter_service.RunAssetDiscoveryRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.RunAssetDiscoveryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.RunAssetDiscoveryRequest): + request = securitycenter_service.RunAssetDiscoveryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent + if parent is not None: + request.parent = parent # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1586,23 +1676,29 @@ def set_finding_state( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name, state, start_time]): + has_flattened_params = any([name, state, start_time]) + 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." ) - request = securitycenter_service.SetFindingStateRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.SetFindingStateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.SetFindingStateRequest): + request = securitycenter_service.SetFindingStateRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name - if state is not None: - request.state = state - if start_time is not None: - request.start_time = start_time + if name is not None: + request.name = name + if state is not None: + request.state = state + if start_time is not None: + request.start_time = start_time # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1723,7 +1819,8 @@ def set_iam_policy( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([resource]): + has_flattened_params = any([resource]) + 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." @@ -1737,11 +1834,11 @@ def set_iam_policy( elif not request: request = iam_policy.SetIamPolicyRequest() - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if resource is not None: - request.resource = resource + if resource is not None: + request.resource = resource # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1806,7 +1903,8 @@ def test_iam_permissions( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([resource, permissions]): + has_flattened_params = any([resource, permissions]) + 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." @@ -1820,14 +1918,14 @@ def test_iam_permissions( elif not request: request = iam_policy.TestIamPermissionsRequest() - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if resource is not None: - request.resource = resource + if resource is not None: + request.resource = resource - if permissions: - request.permissions.extend(permissions) + if permissions: + request.permissions.extend(permissions) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1895,19 +1993,25 @@ def update_finding( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([finding]): + has_flattened_params = any([finding]) + 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." ) - request = securitycenter_service.UpdateFindingRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.UpdateFindingRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateFindingRequest): + request = securitycenter_service.UpdateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if finding is not None: - request.finding = finding + if finding is not None: + request.finding = finding # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1978,21 +2082,29 @@ def update_notification_config( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([notification_config, update_mask]): + has_flattened_params = any([notification_config, update_mask]) + 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." ) - request = securitycenter_service.UpdateNotificationConfigRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.UpdateNotificationConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, securitycenter_service.UpdateNotificationConfigRequest + ): + request = securitycenter_service.UpdateNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if notification_config is not None: - request.notification_config = notification_config - if update_mask is not None: - request.update_mask = update_mask + if notification_config is not None: + request.notification_config = notification_config + 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. @@ -2052,19 +2164,27 @@ def update_organization_settings( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([organization_settings]): + has_flattened_params = any([organization_settings]) + 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." ) - request = securitycenter_service.UpdateOrganizationSettingsRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.UpdateOrganizationSettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, securitycenter_service.UpdateOrganizationSettingsRequest + ): + request = securitycenter_service.UpdateOrganizationSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if organization_settings is not None: - request.organization_settings = organization_settings + if organization_settings is not None: + request.organization_settings = organization_settings # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -2127,19 +2247,25 @@ def update_source( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([source]): + has_flattened_params = any([source]) + 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." ) - request = securitycenter_service.UpdateSourceRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.UpdateSourceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateSourceRequest): + request = securitycenter_service.UpdateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if source is not None: - request.source = source + if source is not None: + request.source = source # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -2202,19 +2328,25 @@ def update_security_marks( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([security_marks]): + has_flattened_params = any([security_marks]) + 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." ) - request = securitycenter_service.UpdateSecurityMarksRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.UpdateSecurityMarksRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): + request = securitycenter_service.UpdateSecurityMarksRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if security_marks is not None: - request.security_marks = security_marks + if security_marks is not None: + request.security_marks = security_marks # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. diff --git a/google/cloud/securitycenter_v1/services/security_center/transports/base.py b/google/cloud/securitycenter_v1/services/security_center/transports/base.py index d606ce76..c00ab831 100644 --- a/google/cloud/securitycenter_v1/services/security_center/transports/base.py +++ b/google/cloud/securitycenter_v1/services/security_center/transports/base.py @@ -22,6 +22,7 @@ from google import auth from google.api_core import exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore from google.auth import credentials # type: ignore diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py b/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py index 2ddb1751..14631074 100644 --- a/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py +++ b/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py @@ -62,16 +62,16 @@ class SecurityCenterAsyncClient: DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + + source_path = staticmethod(SecurityCenterClient.source_path) + organization_settings_path = staticmethod( SecurityCenterClient.organization_settings_path ) - security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) - finding_path = staticmethod(SecurityCenterClient.finding_path) - source_path = staticmethod(SecurityCenterClient.source_path) - from_service_account_file = SecurityCenterClient.from_service_account_file from_service_account_json = from_service_account_file diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/client.py b/google/cloud/securitycenter_v1beta1/services/security_center/client.py index 1c9cabce..2996fa09 100644 --- a/google/cloud/securitycenter_v1beta1/services/security_center/client.py +++ b/google/cloud/securitycenter_v1beta1/services/security_center/client.py @@ -347,21 +347,27 @@ def create_source( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent, source]): + has_flattened_params = any([parent, source]) + 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." ) - request = securitycenter_service.CreateSourceRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.CreateSourceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.CreateSourceRequest): + request = securitycenter_service.CreateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent - if source is not None: - request.source = source + if parent is not None: + request.parent = parent + if source is not None: + request.source = source # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -443,23 +449,29 @@ def create_finding( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent, finding_id, finding]): + has_flattened_params = any([parent, finding_id, finding]) + 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." ) - request = securitycenter_service.CreateFindingRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.CreateFindingRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.CreateFindingRequest): + request = securitycenter_service.CreateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent - if finding_id is not None: - request.finding_id = finding_id - if finding is not None: - request.finding = finding + if parent is not None: + request.parent = parent + if finding_id is not None: + request.finding_id = finding_id + if finding is not None: + request.finding = finding # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -580,7 +592,8 @@ def get_iam_policy( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([resource]): + has_flattened_params = any([resource]) + 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." @@ -594,11 +607,11 @@ def get_iam_policy( elif not request: request = iam_policy.GetIamPolicyRequest() - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if resource is not None: - request.resource = resource + if resource is not None: + request.resource = resource # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -655,19 +668,27 @@ def get_organization_settings( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + 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." ) - request = securitycenter_service.GetOrganizationSettingsRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GetOrganizationSettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, securitycenter_service.GetOrganizationSettingsRequest + ): + request = securitycenter_service.GetOrganizationSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -729,19 +750,25 @@ def get_source( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + 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." ) - request = securitycenter_service.GetSourceRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GetSourceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GetSourceRequest): + request = securitycenter_service.GetSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -792,7 +819,12 @@ def group_assets( """ # Create or coerce a protobuf request object. - request = securitycenter_service.GroupAssetsRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GroupAssetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GroupAssetsRequest): + request = securitycenter_service.GroupAssetsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -880,21 +912,27 @@ def group_findings( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent, group_by]): + has_flattened_params = any([parent, group_by]) + 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." ) - request = securitycenter_service.GroupFindingsRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GroupFindingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GroupFindingsRequest): + request = securitycenter_service.GroupFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -948,7 +986,12 @@ def list_assets( """ # Create or coerce a protobuf request object. - request = securitycenter_service.ListAssetsRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListAssetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.ListAssetsRequest): + request = securitycenter_service.ListAssetsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1008,7 +1051,12 @@ def list_findings( """ # Create or coerce a protobuf request object. - request = securitycenter_service.ListFindingsRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListFindingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.ListFindingsRequest): + request = securitycenter_service.ListFindingsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1071,19 +1119,25 @@ def list_sources( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): + has_flattened_params = any([parent]) + 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." ) - request = securitycenter_service.ListSourcesRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListSourcesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.ListSourcesRequest): + request = securitycenter_service.ListSourcesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent + if parent is not None: + request.parent = parent # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1165,19 +1219,25 @@ def run_asset_discovery( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): + has_flattened_params = any([parent]) + 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." ) - request = securitycenter_service.RunAssetDiscoveryRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.RunAssetDiscoveryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.RunAssetDiscoveryRequest): + request = securitycenter_service.RunAssetDiscoveryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent + if parent is not None: + request.parent = parent # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1264,23 +1324,29 @@ def set_finding_state( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name, state, start_time]): + has_flattened_params = any([name, state, start_time]) + 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." ) - request = securitycenter_service.SetFindingStateRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.SetFindingStateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.SetFindingStateRequest): + request = securitycenter_service.SetFindingStateRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name - if state is not None: - request.state = state - if start_time is not None: - request.start_time = start_time + if name is not None: + request.name = name + if state is not None: + request.state = state + if start_time is not None: + request.start_time = start_time # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1401,7 +1467,8 @@ def set_iam_policy( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([resource]): + has_flattened_params = any([resource]) + 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." @@ -1415,11 +1482,11 @@ def set_iam_policy( elif not request: request = iam_policy.SetIamPolicyRequest() - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if resource is not None: - request.resource = resource + if resource is not None: + request.resource = resource # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1484,7 +1551,8 @@ def test_iam_permissions( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([resource, permissions]): + has_flattened_params = any([resource, permissions]) + 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." @@ -1498,14 +1566,14 @@ def test_iam_permissions( elif not request: request = iam_policy.TestIamPermissionsRequest() - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if resource is not None: - request.resource = resource + if resource is not None: + request.resource = resource - if permissions: - request.permissions.extend(permissions) + if permissions: + request.permissions.extend(permissions) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1573,19 +1641,25 @@ def update_finding( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([finding]): + has_flattened_params = any([finding]) + 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." ) - request = securitycenter_service.UpdateFindingRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.UpdateFindingRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateFindingRequest): + request = securitycenter_service.UpdateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if finding is not None: - request.finding = finding + if finding is not None: + request.finding = finding # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1643,19 +1717,27 @@ def update_organization_settings( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([organization_settings]): + has_flattened_params = any([organization_settings]) + 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." ) - request = securitycenter_service.UpdateOrganizationSettingsRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.UpdateOrganizationSettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, securitycenter_service.UpdateOrganizationSettingsRequest + ): + request = securitycenter_service.UpdateOrganizationSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if organization_settings is not None: - request.organization_settings = organization_settings + if organization_settings is not None: + request.organization_settings = organization_settings # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1718,19 +1800,25 @@ def update_source( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([source]): + has_flattened_params = any([source]) + 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." ) - request = securitycenter_service.UpdateSourceRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.UpdateSourceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateSourceRequest): + request = securitycenter_service.UpdateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if source is not None: - request.source = source + if source is not None: + request.source = source # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1793,19 +1881,25 @@ def update_security_marks( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([security_marks]): + has_flattened_params = any([security_marks]) + 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." ) - request = securitycenter_service.UpdateSecurityMarksRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.UpdateSecurityMarksRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): + request = securitycenter_service.UpdateSecurityMarksRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if security_marks is not None: - request.security_marks = security_marks + if security_marks is not None: + request.security_marks = security_marks # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py b/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py index 64aa9985..52252676 100644 --- a/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py +++ b/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py @@ -22,6 +22,7 @@ from google import auth from google.api_core import exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore from google.auth import credentials # type: ignore diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py index 06704255..6559a055 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py @@ -70,18 +70,18 @@ class SecurityCenterAsyncClient: finding_path = staticmethod(SecurityCenterClient.finding_path) - security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + source_path = staticmethod(SecurityCenterClient.source_path) notification_config_path = staticmethod( SecurityCenterClient.notification_config_path ) + security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + organization_settings_path = staticmethod( SecurityCenterClient.organization_settings_path ) - source_path = staticmethod(SecurityCenterClient.source_path) - from_service_account_file = SecurityCenterClient.from_service_account_file from_service_account_json = from_service_account_file diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py index bdca86ae..80c66f10 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py @@ -369,21 +369,27 @@ def create_source( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent, source]): + has_flattened_params = any([parent, source]) + 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." ) - request = securitycenter_service.CreateSourceRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.CreateSourceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.CreateSourceRequest): + request = securitycenter_service.CreateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent - if source is not None: - request.source = source + if parent is not None: + request.parent = parent + if source is not None: + request.source = source # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -465,23 +471,29 @@ def create_finding( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent, finding_id, finding]): + has_flattened_params = any([parent, finding_id, finding]) + 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." ) - request = securitycenter_service.CreateFindingRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.CreateFindingRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.CreateFindingRequest): + request = securitycenter_service.CreateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent - if finding_id is not None: - request.finding_id = finding_id - if finding is not None: - request.finding = finding + if parent is not None: + request.parent = parent + if finding_id is not None: + request.finding_id = finding_id + if finding is not None: + request.finding = finding # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -561,23 +573,31 @@ def create_notification_config( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent, config_id, notification_config]): + has_flattened_params = any([parent, config_id, notification_config]) + 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." ) - request = securitycenter_service.CreateNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if config_id is not None: - request.config_id = config_id - if notification_config is not None: - request.notification_config = notification_config + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.CreateNotificationConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, securitycenter_service.CreateNotificationConfigRequest + ): + request = securitycenter_service.CreateNotificationConfigRequest(request) + + # If we have keyword arguments corresponding to fields on the + # request, apply these. + + if parent is not None: + request.parent = parent + if config_id is not None: + request.config_id = config_id + if notification_config is not None: + request.notification_config = notification_config # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -629,19 +649,27 @@ def delete_notification_config( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + 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." ) - request = securitycenter_service.DeleteNotificationConfigRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.DeleteNotificationConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, securitycenter_service.DeleteNotificationConfigRequest + ): + request = securitycenter_service.DeleteNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -763,7 +791,8 @@ def get_iam_policy( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([resource]): + has_flattened_params = any([resource]) + 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." @@ -777,11 +806,11 @@ def get_iam_policy( elif not request: request = iam_policy.GetIamPolicyRequest() - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if resource is not None: - request.resource = resource + if resource is not None: + request.resource = resource # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -842,19 +871,25 @@ def get_notification_config( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + 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." ) - request = securitycenter_service.GetNotificationConfigRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GetNotificationConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): + request = securitycenter_service.GetNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -911,19 +946,27 @@ def get_organization_settings( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + 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." ) - request = securitycenter_service.GetOrganizationSettingsRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GetOrganizationSettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, securitycenter_service.GetOrganizationSettingsRequest + ): + request = securitycenter_service.GetOrganizationSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -985,19 +1028,25 @@ def get_source( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name]): + has_flattened_params = any([name]) + 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." ) - request = securitycenter_service.GetSourceRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GetSourceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GetSourceRequest): + request = securitycenter_service.GetSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name + if name is not None: + request.name = name # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1048,7 +1097,12 @@ def group_assets( """ # Create or coerce a protobuf request object. - request = securitycenter_service.GroupAssetsRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GroupAssetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GroupAssetsRequest): + request = securitycenter_service.GroupAssetsRequest(request) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1141,21 +1195,27 @@ def group_findings( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent, group_by]): + has_flattened_params = any([parent, group_by]) + 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." ) - request = securitycenter_service.GroupFindingsRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.GroupFindingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.GroupFindingsRequest): + request = securitycenter_service.GroupFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by + if parent is not None: + request.parent = parent + if group_by is not None: + request.group_by = group_by # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1217,19 +1277,25 @@ def list_assets( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): + has_flattened_params = any([parent]) + 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." ) - request = securitycenter_service.ListAssetsRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListAssetsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.ListAssetsRequest): + request = securitycenter_service.ListAssetsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent + if parent is not None: + request.parent = parent # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1300,19 +1366,25 @@ def list_findings( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): + has_flattened_params = any([parent]) + 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." ) - request = securitycenter_service.ListFindingsRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListFindingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.ListFindingsRequest): + request = securitycenter_service.ListFindingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent + if parent is not None: + request.parent = parent # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1377,19 +1449,27 @@ def list_notification_configs( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): + has_flattened_params = any([parent]) + 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." ) - request = securitycenter_service.ListNotificationConfigsRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListNotificationConfigsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, securitycenter_service.ListNotificationConfigsRequest + ): + request = securitycenter_service.ListNotificationConfigsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent + if parent is not None: + request.parent = parent # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1454,19 +1534,25 @@ def list_sources( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): + has_flattened_params = any([parent]) + 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." ) - request = securitycenter_service.ListSourcesRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.ListSourcesRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.ListSourcesRequest): + request = securitycenter_service.ListSourcesRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent + if parent is not None: + request.parent = parent # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1536,19 +1622,25 @@ def run_asset_discovery( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): + has_flattened_params = any([parent]) + 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." ) - request = securitycenter_service.RunAssetDiscoveryRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.RunAssetDiscoveryRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.RunAssetDiscoveryRequest): + request = securitycenter_service.RunAssetDiscoveryRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if parent is not None: - request.parent = parent + if parent is not None: + request.parent = parent # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1635,23 +1727,29 @@ def set_finding_state( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([name, state, start_time]): + has_flattened_params = any([name, state, start_time]) + 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." ) - request = securitycenter_service.SetFindingStateRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.SetFindingStateRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.SetFindingStateRequest): + request = securitycenter_service.SetFindingStateRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if name is not None: - request.name = name - if state is not None: - request.state = state - if start_time is not None: - request.start_time = start_time + if name is not None: + request.name = name + if state is not None: + request.state = state + if start_time is not None: + request.start_time = start_time # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1772,7 +1870,8 @@ def set_iam_policy( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([resource]): + has_flattened_params = any([resource]) + 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." @@ -1786,11 +1885,11 @@ def set_iam_policy( elif not request: request = iam_policy.SetIamPolicyRequest() - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if resource is not None: - request.resource = resource + if resource is not None: + request.resource = resource # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1855,7 +1954,8 @@ def test_iam_permissions( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([resource, permissions]): + has_flattened_params = any([resource, permissions]) + 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." @@ -1869,14 +1969,14 @@ def test_iam_permissions( elif not request: request = iam_policy.TestIamPermissionsRequest() - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if resource is not None: - request.resource = resource + if resource is not None: + request.resource = resource - if permissions: - request.permissions.extend(permissions) + if permissions: + request.permissions.extend(permissions) # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -1958,21 +2058,27 @@ def update_finding( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([finding, update_mask]): + has_flattened_params = any([finding, update_mask]) + 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." ) - request = securitycenter_service.UpdateFindingRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.UpdateFindingRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateFindingRequest): + request = securitycenter_service.UpdateFindingRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if finding is not None: - request.finding = finding - if update_mask is not None: - request.update_mask = update_mask + if finding is not None: + request.finding = finding + 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. @@ -2044,21 +2150,29 @@ def update_notification_config( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([notification_config, update_mask]): + has_flattened_params = any([notification_config, update_mask]) + 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." ) - request = securitycenter_service.UpdateNotificationConfigRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.UpdateNotificationConfigRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, securitycenter_service.UpdateNotificationConfigRequest + ): + request = securitycenter_service.UpdateNotificationConfigRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if notification_config is not None: - request.notification_config = notification_config - if update_mask is not None: - request.update_mask = update_mask + if notification_config is not None: + request.notification_config = notification_config + 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. @@ -2118,19 +2232,27 @@ def update_organization_settings( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([organization_settings]): + has_flattened_params = any([organization_settings]) + 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." ) - request = securitycenter_service.UpdateOrganizationSettingsRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.UpdateOrganizationSettingsRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance( + request, securitycenter_service.UpdateOrganizationSettingsRequest + ): + request = securitycenter_service.UpdateOrganizationSettingsRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if organization_settings is not None: - request.organization_settings = organization_settings + if organization_settings is not None: + request.organization_settings = organization_settings # Wrap the RPC method; this adds retry and timeout information, # and friendly error handling. @@ -2202,21 +2324,27 @@ def update_source( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([source, update_mask]): + has_flattened_params = any([source, update_mask]) + 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." ) - request = securitycenter_service.UpdateSourceRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.UpdateSourceRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateSourceRequest): + request = securitycenter_service.UpdateSourceRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if source is not None: - request.source = source - if update_mask is not None: - request.update_mask = update_mask + if source is not None: + request.source = source + 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. @@ -2291,21 +2419,27 @@ def update_security_marks( # Create or coerce a protobuf request object. # Sanity check: If we got a request object, we should *not* have # gotten any keyword arguments that map to the request. - if request is not None and any([security_marks, update_mask]): + has_flattened_params = any([security_marks, update_mask]) + 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." ) - request = securitycenter_service.UpdateSecurityMarksRequest(request) + # Minor optimization to avoid making a copy if the user passes + # in a securitycenter_service.UpdateSecurityMarksRequest. + # There's no risk of modifying the input as we've already verified + # there are no flattened fields. + if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): + request = securitycenter_service.UpdateSecurityMarksRequest(request) - # If we have keyword arguments corresponding to fields on the - # request, apply these. + # If we have keyword arguments corresponding to fields on the + # request, apply these. - if security_marks is not None: - request.security_marks = security_marks - if update_mask is not None: - request.update_mask = update_mask + if security_marks is not None: + request.security_marks = security_marks + 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. diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py index 47b6ac39..dd77306b 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py @@ -22,6 +22,7 @@ from google import auth from google.api_core import exceptions # type: ignore from google.api_core import gapic_v1 # type: ignore +from google.api_core import retry as retries # type: ignore from google.api_core import operations_v1 # type: ignore from google.auth import credentials # type: ignore diff --git a/synth.metadata b/synth.metadata index ca9b7239..93f3db0c 100644 --- a/synth.metadata +++ b/synth.metadata @@ -11,8 +11,8 @@ "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "706053bbfb3f16ef752e513c2898a1f26cdd8e41", - "internalRef": "323803770" + "sha": "8cda089accaead072caea33c5081be8a4b8f9ea7", + "internalRef": "324035013" } }, { From 6dcada9bc75d2d411ece89bd704adbaef1e94cfd Mon Sep 17 00:00:00 2001 From: yoshi-automation Date: Sat, 1 Aug 2020 11:26:58 -0700 Subject: [PATCH 13/17] chore: move gaming to python microgenerator bazel rules PiperOrigin-RevId: 324294521 Source-Author: Google APIs Source-Date: Fri Jul 31 15:17:19 2020 -0700 Source-Repo: googleapis/googleapis Source-Sha: 868615a5c1c1059c636bb3d82a555edb1d5a251e Source-Link: https://github.com/googleapis/googleapis/commit/868615a5c1c1059c636bb3d82a555edb1d5a251e --- .../services/security_center/async_client.py | 8 ++--- .../services/security_center/async_client.py | 8 ++--- .../services/security_center/async_client.py | 34 +++++++++---------- .../security_center/transports/base.py | 22 ++++++------ synth.metadata | 4 +-- 5 files changed, 38 insertions(+), 38 deletions(-) diff --git a/google/cloud/securitycenter_v1/services/security_center/async_client.py b/google/cloud/securitycenter_v1/services/security_center/async_client.py index 658ab5b0..147b43bd 100644 --- a/google/cloud/securitycenter_v1/services/security_center/async_client.py +++ b/google/cloud/securitycenter_v1/services/security_center/async_client.py @@ -66,20 +66,20 @@ class SecurityCenterAsyncClient: DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - finding_path = staticmethod(SecurityCenterClient.finding_path) - security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + finding_path = staticmethod(SecurityCenterClient.finding_path) + notification_config_path = staticmethod( SecurityCenterClient.notification_config_path ) + source_path = staticmethod(SecurityCenterClient.source_path) + organization_settings_path = staticmethod( SecurityCenterClient.organization_settings_path ) - source_path = staticmethod(SecurityCenterClient.source_path) - from_service_account_file = SecurityCenterClient.from_service_account_file from_service_account_json = from_service_account_file diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py b/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py index 14631074..2be877e7 100644 --- a/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py +++ b/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py @@ -62,16 +62,16 @@ class SecurityCenterAsyncClient: DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) - - source_path = staticmethod(SecurityCenterClient.source_path) - organization_settings_path = staticmethod( SecurityCenterClient.organization_settings_path ) finding_path = staticmethod(SecurityCenterClient.finding_path) + source_path = staticmethod(SecurityCenterClient.source_path) + + security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + from_service_account_file = SecurityCenterClient.from_service_account_file from_service_account_json = from_service_account_file diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py index 6559a055..31718663 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py @@ -68,6 +68,12 @@ class SecurityCenterAsyncClient: DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT + organization_settings_path = staticmethod( + SecurityCenterClient.organization_settings_path + ) + + security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) + finding_path = staticmethod(SecurityCenterClient.finding_path) source_path = staticmethod(SecurityCenterClient.source_path) @@ -76,12 +82,6 @@ class SecurityCenterAsyncClient: SecurityCenterClient.notification_config_path ) - security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) - - organization_settings_path = staticmethod( - SecurityCenterClient.organization_settings_path - ) - from_service_account_file = SecurityCenterClient.from_service_account_file from_service_account_json = from_service_account_file @@ -614,7 +614,7 @@ async def get_iam_policy( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=60.0, @@ -699,7 +699,7 @@ async def get_notification_config( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=60.0, @@ -780,7 +780,7 @@ async def get_organization_settings( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=60.0, @@ -864,7 +864,7 @@ async def get_source( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=60.0, @@ -927,7 +927,7 @@ async def group_assets( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=480.0, @@ -1046,7 +1046,7 @@ async def group_findings( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=480.0, @@ -1132,7 +1132,7 @@ async def list_assets( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=480.0, @@ -1227,7 +1227,7 @@ async def list_findings( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=480.0, @@ -1316,7 +1316,7 @@ async def list_notification_configs( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=60.0, @@ -1403,7 +1403,7 @@ async def list_sources( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=60.0, @@ -1837,7 +1837,7 @@ async def test_iam_permissions( maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=60.0, diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py index dd77306b..d506c7bc 100644 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py +++ b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py @@ -143,7 +143,7 @@ def _prep_wrapped_messages(self): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=60.0, @@ -156,7 +156,7 @@ def _prep_wrapped_messages(self): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=60.0, @@ -169,7 +169,7 @@ def _prep_wrapped_messages(self): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=60.0, @@ -182,7 +182,7 @@ def _prep_wrapped_messages(self): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=60.0, @@ -195,7 +195,7 @@ def _prep_wrapped_messages(self): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=480.0, @@ -208,7 +208,7 @@ def _prep_wrapped_messages(self): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=480.0, @@ -221,7 +221,7 @@ def _prep_wrapped_messages(self): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=480.0, @@ -234,7 +234,7 @@ def _prep_wrapped_messages(self): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=480.0, @@ -247,7 +247,7 @@ def _prep_wrapped_messages(self): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=60.0, @@ -260,7 +260,7 @@ def _prep_wrapped_messages(self): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=60.0, @@ -284,7 +284,7 @@ def _prep_wrapped_messages(self): maximum=60.0, multiplier=1.3, predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, + exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, ), ), default_timeout=60.0, diff --git a/synth.metadata b/synth.metadata index 93f3db0c..d785b01e 100644 --- a/synth.metadata +++ b/synth.metadata @@ -11,8 +11,8 @@ "git": { "name": "googleapis", "remote": "https://github.com/googleapis/googleapis.git", - "sha": "8cda089accaead072caea33c5081be8a4b8f9ea7", - "internalRef": "324035013" + "sha": "868615a5c1c1059c636bb3d82a555edb1d5a251e", + "internalRef": "324294521" } }, { From 1cc4d1ffb5d64301d891d4ee95e429e4be1e4cf4 Mon Sep 17 00:00:00 2001 From: Bu Sun Kim Date: Thu, 10 Sep 2020 16:31:28 +0000 Subject: [PATCH 14/17] manual regen --- .github/snippet-bot.yml | 0 .gitignore | 3 +- .kokoro/build.sh | 8 +- .kokoro/docker/docs/Dockerfile | 98 ++ .kokoro/docker/docs/fetch_gpg_keys.sh | 45 + .kokoro/docs/common.cfg | 21 +- .kokoro/docs/docs-presubmit.cfg | 17 + .kokoro/publish-docs.sh | 39 +- .kokoro/trampoline_v2.sh | 487 +++++++ .trampolinerc | 51 + docs/conf.py | 13 +- docs/gapic/v1beta1/api.rst | 4 +- docs/gapic/v1beta1/types.rst | 4 +- google/cloud/securitycenter_v1/__init__.py | 102 +- .../gapic/security_center_client.py | 1268 ++++++++--------- .../gapic/security_center_client_config.py | 169 ++- .../security_center_grpc_transport.py | 114 +- .../securitycenter_v1/proto/asset_pb2.py | 2 +- .../securitycenter_v1/proto/finding.proto | 8 +- .../securitycenter_v1/proto/finding_pb2.py | 12 +- .../proto/notification_config_pb2.py | 2 +- .../proto/notification_message_pb2.py | 2 +- .../proto/organization_settings_pb2.py | 2 +- .../securitycenter_v1/proto/resource_pb2.py | 2 +- .../proto/run_asset_discovery_response_pb2.py | 2 +- .../proto/security_marks_pb2.py | 2 +- .../proto/securitycenter_service_pb2.py | 2 +- .../securitycenter_v1/proto/source_pb2.py | 2 +- .../cloud/securitycenter_v1beta1/__init__.py | 84 +- .../gapic/security_center_client.py | 37 +- .../gapic/security_center_client_config.py | 135 +- .../securitycenter_v1beta1/proto/asset_pb2.py | 66 +- .../proto/finding.proto | 13 +- .../proto/finding_pb2.py | 41 +- .../proto/organization_settings_pb2.py | 6 +- .../proto/run_asset_discovery_response_pb2.py | 2 +- .../proto/security_marks_pb2.py | 10 +- .../proto/securitycenter_service_pb2.py | 2 +- .../proto/source_pb2.py | 12 +- .../securitycenter_v1p1beta1/__init__.py | 102 +- .../securitycenter_v1p1beta1/gapic/enums.py | 18 + .../gapic/security_center_client.py | 13 +- .../gapic/security_center_client_config.py | 155 +- .../proto/asset_pb2.py | 2 +- .../proto/finding.proto | 29 +- .../proto/finding_pb2.py | 104 +- .../proto/notification_config_pb2.py | 2 +- .../proto/notification_message_pb2.py | 2 +- .../proto/organization_settings_pb2.py | 2 +- .../proto/resource_pb2.py | 2 +- .../proto/run_asset_discovery_response_pb2.py | 2 +- .../proto/security_marks_pb2.py | 2 +- .../proto/securitycenter_service.proto | 111 +- .../proto/securitycenter_service_pb2.py | 93 +- .../proto/securitycenter_service_pb2_grpc.py | 6 +- .../proto/source_pb2.py | 2 +- noxfile.py | 39 + scripts/decrypt-secrets.sh | 15 +- synth.metadata | 16 +- .../v1/test_security_center_client_v1.py | 380 ++--- .../test_security_center_client_v1beta1.py | 12 +- 61 files changed, 2430 insertions(+), 1568 deletions(-) create mode 100644 .github/snippet-bot.yml create mode 100644 .kokoro/docker/docs/Dockerfile create mode 100755 .kokoro/docker/docs/fetch_gpg_keys.sh create mode 100644 .kokoro/docs/docs-presubmit.cfg create mode 100755 .kokoro/trampoline_v2.sh create mode 100644 .trampolinerc diff --git a/.github/snippet-bot.yml b/.github/snippet-bot.yml new file mode 100644 index 00000000..e69de29b diff --git a/.gitignore b/.gitignore index b87e1ed5..b9daa52f 100644 --- a/.gitignore +++ b/.gitignore @@ -46,6 +46,7 @@ pip-log.txt # Built documentation docs/_build bigquery/docs/generated +docs.metadata # Virtual environment env/ @@ -57,4 +58,4 @@ system_tests/local_test_setup # Make sure a generated file isn't accidentally committed. pylintrc -pylintrc.test \ No newline at end of file +pylintrc.test diff --git a/.kokoro/build.sh b/.kokoro/build.sh index 0f29e059..662b06bc 100755 --- a/.kokoro/build.sh +++ b/.kokoro/build.sh @@ -36,4 +36,10 @@ python3.6 -m pip uninstall --yes --quiet nox-automation python3.6 -m pip install --upgrade --quiet nox python3.6 -m nox --version -python3.6 -m nox +# If NOX_SESSION is set, it only runs the specified session, +# otherwise run all the sessions. +if [[ -n "${NOX_SESSION:-}" ]]; then + python3.6 -m nox -s "${NOX_SESSION:-}" +else + python3.6 -m nox +fi diff --git a/.kokoro/docker/docs/Dockerfile b/.kokoro/docker/docs/Dockerfile new file mode 100644 index 00000000..412b0b56 --- /dev/null +++ b/.kokoro/docker/docs/Dockerfile @@ -0,0 +1,98 @@ +# Copyright 2020 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 ubuntu:20.04 + +ENV DEBIAN_FRONTEND noninteractive + +# Ensure local Python is preferred over distribution Python. +ENV PATH /usr/local/bin:$PATH + +# Install dependencies. +RUN apt-get update \ + && apt-get install -y --no-install-recommends \ + apt-transport-https \ + build-essential \ + ca-certificates \ + curl \ + dirmngr \ + git \ + gpg-agent \ + graphviz \ + libbz2-dev \ + libdb5.3-dev \ + libexpat1-dev \ + libffi-dev \ + liblzma-dev \ + libreadline-dev \ + libsnappy-dev \ + libssl-dev \ + libsqlite3-dev \ + portaudio19-dev \ + redis-server \ + software-properties-common \ + ssh \ + sudo \ + tcl \ + tcl-dev \ + tk \ + tk-dev \ + uuid-dev \ + wget \ + zlib1g-dev \ + && add-apt-repository universe \ + && apt-get update \ + && apt-get -y install jq \ + && apt-get clean autoclean \ + && apt-get autoremove -y \ + && rm -rf /var/lib/apt/lists/* \ + && rm -f /var/cache/apt/archives/*.deb + + +COPY fetch_gpg_keys.sh /tmp +# Install the desired versions of Python. +RUN set -ex \ + && export GNUPGHOME="$(mktemp -d)" \ + && echo "disable-ipv6" >> "${GNUPGHOME}/dirmngr.conf" \ + && /tmp/fetch_gpg_keys.sh \ + && for PYTHON_VERSION in 3.7.8 3.8.5; do \ + wget --no-check-certificate -O python-${PYTHON_VERSION}.tar.xz "https://www.python.org/ftp/python/${PYTHON_VERSION%%[a-z]*}/Python-$PYTHON_VERSION.tar.xz" \ + && wget --no-check-certificate -O python-${PYTHON_VERSION}.tar.xz.asc "https://www.python.org/ftp/python/${PYTHON_VERSION%%[a-z]*}/Python-$PYTHON_VERSION.tar.xz.asc" \ + && gpg --batch --verify python-${PYTHON_VERSION}.tar.xz.asc python-${PYTHON_VERSION}.tar.xz \ + && rm -r python-${PYTHON_VERSION}.tar.xz.asc \ + && mkdir -p /usr/src/python-${PYTHON_VERSION} \ + && tar -xJC /usr/src/python-${PYTHON_VERSION} --strip-components=1 -f python-${PYTHON_VERSION}.tar.xz \ + && rm python-${PYTHON_VERSION}.tar.xz \ + && cd /usr/src/python-${PYTHON_VERSION} \ + && ./configure \ + --enable-shared \ + # This works only on Python 2.7 and throws a warning on every other + # version, but seems otherwise harmless. + --enable-unicode=ucs4 \ + --with-system-ffi \ + --without-ensurepip \ + && make -j$(nproc) \ + && make install \ + && ldconfig \ + ; done \ + && rm -rf "${GNUPGHOME}" \ + && rm -rf /usr/src/python* \ + && rm -rf ~/.cache/ + +RUN wget -O /tmp/get-pip.py 'https://bootstrap.pypa.io/get-pip.py' \ + && python3.7 /tmp/get-pip.py \ + && python3.8 /tmp/get-pip.py \ + && rm /tmp/get-pip.py + +CMD ["python3.7"] diff --git a/.kokoro/docker/docs/fetch_gpg_keys.sh b/.kokoro/docker/docs/fetch_gpg_keys.sh new file mode 100755 index 00000000..d653dd86 --- /dev/null +++ b/.kokoro/docker/docs/fetch_gpg_keys.sh @@ -0,0 +1,45 @@ +#!/bin/bash +# Copyright 2020 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. + +# A script to fetch gpg keys with retry. +# Avoid jinja parsing the file. +# + +function retry { + if [[ "${#}" -le 1 ]]; then + echo "Usage: ${0} retry_count commands.." + exit 1 + fi + local retries=${1} + local command="${@:2}" + until [[ "${retries}" -le 0 ]]; do + $command && return 0 + if [[ $? -ne 0 ]]; then + echo "command failed, retrying" + ((retries--)) + fi + done + return 1 +} + +# 3.6.9, 3.7.5 (Ned Deily) +retry 3 gpg --keyserver ha.pool.sks-keyservers.net --recv-keys \ + 0D96DF4D4110E5C43FBFB17F2D347EA6AA65421D + +# 3.8.0 (Łukasz Langa) +retry 3 gpg --keyserver ha.pool.sks-keyservers.net --recv-keys \ + E3FF2839C048B25C084DEBE9B26995E310250568 + +# diff --git a/.kokoro/docs/common.cfg b/.kokoro/docs/common.cfg index 28f1b005..571f0e74 100644 --- a/.kokoro/docs/common.cfg +++ b/.kokoro/docs/common.cfg @@ -11,12 +11,12 @@ action { gfile_resources: "/bigstore/cloud-devrel-kokoro-resources/trampoline" # Use the trampoline script to run in docker. -build_file: "python-securitycenter/.kokoro/trampoline.sh" +build_file: "python-securitycenter/.kokoro/trampoline_v2.sh" # Configure the docker image for kokoro-trampoline. env_vars: { key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/python-multi" + value: "gcr.io/cloud-devrel-kokoro-resources/python-lib-docs" } env_vars: { key: "TRAMPOLINE_BUILD_FILE" @@ -28,6 +28,23 @@ env_vars: { value: "docs-staging" } +env_vars: { + key: "V2_STAGING_BUCKET" + value: "docs-staging-v2-staging" +} + +# It will upload the docker image after successful builds. +env_vars: { + key: "TRAMPOLINE_IMAGE_UPLOAD" + value: "true" +} + +# It will always build the docker image. +env_vars: { + key: "TRAMPOLINE_DOCKERFILE" + value: ".kokoro/docker/docs/Dockerfile" +} + # Fetch the token needed for reporting release status to GitHub before_action { fetch_keystore { diff --git a/.kokoro/docs/docs-presubmit.cfg b/.kokoro/docs/docs-presubmit.cfg new file mode 100644 index 00000000..11181078 --- /dev/null +++ b/.kokoro/docs/docs-presubmit.cfg @@ -0,0 +1,17 @@ +# Format: //devtools/kokoro/config/proto/build.proto + +env_vars: { + key: "STAGING_BUCKET" + value: "gcloud-python-test" +} + +env_vars: { + key: "V2_STAGING_BUCKET" + value: "gcloud-python-test" +} + +# We only upload the image in the main `docs` build. +env_vars: { + key: "TRAMPOLINE_IMAGE_UPLOAD" + value: "false" +} diff --git a/.kokoro/publish-docs.sh b/.kokoro/publish-docs.sh index ff7f2730..8acb14e8 100755 --- a/.kokoro/publish-docs.sh +++ b/.kokoro/publish-docs.sh @@ -18,26 +18,16 @@ set -eo pipefail # Disable buffering, so that the logs stream through. export PYTHONUNBUFFERED=1 -cd github/python-securitycenter - -# Remove old nox -python3.6 -m pip uninstall --yes --quiet nox-automation +export PATH="${HOME}/.local/bin:${PATH}" # Install nox -python3.6 -m pip install --upgrade --quiet nox -python3.6 -m nox --version +python3 -m pip install --user --upgrade --quiet nox +python3 -m nox --version # build docs nox -s docs -python3 -m pip install gcp-docuploader - -# install a json parser -sudo apt-get update -sudo apt-get -y install software-properties-common -sudo add-apt-repository universe -sudo apt-get update -sudo apt-get -y install jq +python3 -m pip install --user gcp-docuploader # create metadata python3 -m docuploader create-metadata \ @@ -52,4 +42,23 @@ python3 -m docuploader create-metadata \ cat docs.metadata # upload docs -python3 -m docuploader upload docs/_build/html --metadata-file docs.metadata --staging-bucket docs-staging +python3 -m docuploader upload docs/_build/html --metadata-file docs.metadata --staging-bucket "${STAGING_BUCKET}" + + +# docfx yaml files +nox -s docfx + +# create metadata. +python3 -m docuploader create-metadata \ + --name=$(jq --raw-output '.name // empty' .repo-metadata.json) \ + --version=$(python3 setup.py --version) \ + --language=$(jq --raw-output '.language // empty' .repo-metadata.json) \ + --distribution-name=$(python3 setup.py --name) \ + --product-page=$(jq --raw-output '.product_documentation // empty' .repo-metadata.json) \ + --github-repository=$(jq --raw-output '.repo // empty' .repo-metadata.json) \ + --issue-tracker=$(jq --raw-output '.issue_tracker // empty' .repo-metadata.json) + +cat docs.metadata + +# upload docs +python3 -m docuploader upload docs/_build/html/docfx_yaml --metadata-file docs.metadata --destination-prefix docfx --staging-bucket "${V2_STAGING_BUCKET}" diff --git a/.kokoro/trampoline_v2.sh b/.kokoro/trampoline_v2.sh new file mode 100755 index 00000000..719bcd5b --- /dev/null +++ b/.kokoro/trampoline_v2.sh @@ -0,0 +1,487 @@ +#!/usr/bin/env bash +# Copyright 2020 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. + +# trampoline_v2.sh +# +# This script does 3 things. +# +# 1. Prepare the Docker image for the test +# 2. Run the Docker with appropriate flags to run the test +# 3. Upload the newly built Docker image +# +# in a way that is somewhat compatible with trampoline_v1. +# +# To run this script, first download few files from gcs to /dev/shm. +# (/dev/shm is passed into the container as KOKORO_GFILE_DIR). +# +# gsutil cp gs://cloud-devrel-kokoro-resources/python-docs-samples/secrets_viewer_service_account.json /dev/shm +# gsutil cp gs://cloud-devrel-kokoro-resources/python-docs-samples/automl_secrets.txt /dev/shm +# +# Then run the script. +# .kokoro/trampoline_v2.sh +# +# These environment variables are required: +# TRAMPOLINE_IMAGE: The docker image to use. +# TRAMPOLINE_DOCKERFILE: The location of the Dockerfile. +# +# You can optionally change these environment variables: +# TRAMPOLINE_IMAGE_UPLOAD: +# (true|false): Whether to upload the Docker image after the +# successful builds. +# TRAMPOLINE_BUILD_FILE: The script to run in the docker container. +# TRAMPOLINE_WORKSPACE: The workspace path in the docker container. +# Defaults to /workspace. +# Potentially there are some repo specific envvars in .trampolinerc in +# the project root. + + +set -euo pipefail + +TRAMPOLINE_VERSION="2.0.5" + +if command -v tput >/dev/null && [[ -n "${TERM:-}" ]]; then + readonly IO_COLOR_RED="$(tput setaf 1)" + readonly IO_COLOR_GREEN="$(tput setaf 2)" + readonly IO_COLOR_YELLOW="$(tput setaf 3)" + readonly IO_COLOR_RESET="$(tput sgr0)" +else + readonly IO_COLOR_RED="" + readonly IO_COLOR_GREEN="" + readonly IO_COLOR_YELLOW="" + readonly IO_COLOR_RESET="" +fi + +function function_exists { + [ $(LC_ALL=C type -t $1)"" == "function" ] +} + +# Logs a message using the given color. The first argument must be one +# of the IO_COLOR_* variables defined above, such as +# "${IO_COLOR_YELLOW}". The remaining arguments will be logged in the +# given color. The log message will also have an RFC-3339 timestamp +# prepended (in UTC). You can disable the color output by setting +# TERM=vt100. +function log_impl() { + local color="$1" + shift + local timestamp="$(date -u "+%Y-%m-%dT%H:%M:%SZ")" + echo "================================================================" + echo "${color}${timestamp}:" "$@" "${IO_COLOR_RESET}" + echo "================================================================" +} + +# Logs the given message with normal coloring and a timestamp. +function log() { + log_impl "${IO_COLOR_RESET}" "$@" +} + +# Logs the given message in green with a timestamp. +function log_green() { + log_impl "${IO_COLOR_GREEN}" "$@" +} + +# Logs the given message in yellow with a timestamp. +function log_yellow() { + log_impl "${IO_COLOR_YELLOW}" "$@" +} + +# Logs the given message in red with a timestamp. +function log_red() { + log_impl "${IO_COLOR_RED}" "$@" +} + +readonly tmpdir=$(mktemp -d -t ci-XXXXXXXX) +readonly tmphome="${tmpdir}/h" +mkdir -p "${tmphome}" + +function cleanup() { + rm -rf "${tmpdir}" +} +trap cleanup EXIT + +RUNNING_IN_CI="${RUNNING_IN_CI:-false}" + +# The workspace in the container, defaults to /workspace. +TRAMPOLINE_WORKSPACE="${TRAMPOLINE_WORKSPACE:-/workspace}" + +pass_down_envvars=( + # TRAMPOLINE_V2 variables. + # Tells scripts whether they are running as part of CI or not. + "RUNNING_IN_CI" + # Indicates which CI system we're in. + "TRAMPOLINE_CI" + # Indicates the version of the script. + "TRAMPOLINE_VERSION" +) + +log_yellow "Building with Trampoline ${TRAMPOLINE_VERSION}" + +# Detect which CI systems we're in. If we're in any of the CI systems +# we support, `RUNNING_IN_CI` will be true and `TRAMPOLINE_CI` will be +# the name of the CI system. Both envvars will be passing down to the +# container for telling which CI system we're in. +if [[ -n "${KOKORO_BUILD_ID:-}" ]]; then + # descriptive env var for indicating it's on CI. + RUNNING_IN_CI="true" + TRAMPOLINE_CI="kokoro" + if [[ "${TRAMPOLINE_USE_LEGACY_SERVICE_ACCOUNT:-}" == "true" ]]; then + if [[ ! -f "${KOKORO_GFILE_DIR}/kokoro-trampoline.service-account.json" ]]; then + log_red "${KOKORO_GFILE_DIR}/kokoro-trampoline.service-account.json does not exist. Did you forget to mount cloud-devrel-kokoro-resources/trampoline? Aborting." + exit 1 + fi + # This service account will be activated later. + TRAMPOLINE_SERVICE_ACCOUNT="${KOKORO_GFILE_DIR}/kokoro-trampoline.service-account.json" + else + if [[ "${TRAMPOLINE_VERBOSE:-}" == "true" ]]; then + gcloud auth list + fi + log_yellow "Configuring Container Registry access" + gcloud auth configure-docker --quiet + fi + pass_down_envvars+=( + # KOKORO dynamic variables. + "KOKORO_BUILD_NUMBER" + "KOKORO_BUILD_ID" + "KOKORO_JOB_NAME" + "KOKORO_GIT_COMMIT" + "KOKORO_GITHUB_COMMIT" + "KOKORO_GITHUB_PULL_REQUEST_NUMBER" + "KOKORO_GITHUB_PULL_REQUEST_COMMIT" + # For Build Cop Bot + "KOKORO_GITHUB_COMMIT_URL" + "KOKORO_GITHUB_PULL_REQUEST_URL" + ) +elif [[ "${TRAVIS:-}" == "true" ]]; then + RUNNING_IN_CI="true" + TRAMPOLINE_CI="travis" + pass_down_envvars+=( + "TRAVIS_BRANCH" + "TRAVIS_BUILD_ID" + "TRAVIS_BUILD_NUMBER" + "TRAVIS_BUILD_WEB_URL" + "TRAVIS_COMMIT" + "TRAVIS_COMMIT_MESSAGE" + "TRAVIS_COMMIT_RANGE" + "TRAVIS_JOB_NAME" + "TRAVIS_JOB_NUMBER" + "TRAVIS_JOB_WEB_URL" + "TRAVIS_PULL_REQUEST" + "TRAVIS_PULL_REQUEST_BRANCH" + "TRAVIS_PULL_REQUEST_SHA" + "TRAVIS_PULL_REQUEST_SLUG" + "TRAVIS_REPO_SLUG" + "TRAVIS_SECURE_ENV_VARS" + "TRAVIS_TAG" + ) +elif [[ -n "${GITHUB_RUN_ID:-}" ]]; then + RUNNING_IN_CI="true" + TRAMPOLINE_CI="github-workflow" + pass_down_envvars+=( + "GITHUB_WORKFLOW" + "GITHUB_RUN_ID" + "GITHUB_RUN_NUMBER" + "GITHUB_ACTION" + "GITHUB_ACTIONS" + "GITHUB_ACTOR" + "GITHUB_REPOSITORY" + "GITHUB_EVENT_NAME" + "GITHUB_EVENT_PATH" + "GITHUB_SHA" + "GITHUB_REF" + "GITHUB_HEAD_REF" + "GITHUB_BASE_REF" + ) +elif [[ "${CIRCLECI:-}" == "true" ]]; then + RUNNING_IN_CI="true" + TRAMPOLINE_CI="circleci" + pass_down_envvars+=( + "CIRCLE_BRANCH" + "CIRCLE_BUILD_NUM" + "CIRCLE_BUILD_URL" + "CIRCLE_COMPARE_URL" + "CIRCLE_JOB" + "CIRCLE_NODE_INDEX" + "CIRCLE_NODE_TOTAL" + "CIRCLE_PREVIOUS_BUILD_NUM" + "CIRCLE_PROJECT_REPONAME" + "CIRCLE_PROJECT_USERNAME" + "CIRCLE_REPOSITORY_URL" + "CIRCLE_SHA1" + "CIRCLE_STAGE" + "CIRCLE_USERNAME" + "CIRCLE_WORKFLOW_ID" + "CIRCLE_WORKFLOW_JOB_ID" + "CIRCLE_WORKFLOW_UPSTREAM_JOB_IDS" + "CIRCLE_WORKFLOW_WORKSPACE_ID" + ) +fi + +# Configure the service account for pulling the docker image. +function repo_root() { + local dir="$1" + while [[ ! -d "${dir}/.git" ]]; do + dir="$(dirname "$dir")" + done + echo "${dir}" +} + +# Detect the project root. In CI builds, we assume the script is in +# the git tree and traverse from there, otherwise, traverse from `pwd` +# to find `.git` directory. +if [[ "${RUNNING_IN_CI:-}" == "true" ]]; then + PROGRAM_PATH="$(realpath "$0")" + PROGRAM_DIR="$(dirname "${PROGRAM_PATH}")" + PROJECT_ROOT="$(repo_root "${PROGRAM_DIR}")" +else + PROJECT_ROOT="$(repo_root $(pwd))" +fi + +log_yellow "Changing to the project root: ${PROJECT_ROOT}." +cd "${PROJECT_ROOT}" + +# To support relative path for `TRAMPOLINE_SERVICE_ACCOUNT`, we need +# to use this environment variable in `PROJECT_ROOT`. +if [[ -n "${TRAMPOLINE_SERVICE_ACCOUNT:-}" ]]; then + + mkdir -p "${tmpdir}/gcloud" + gcloud_config_dir="${tmpdir}/gcloud" + + log_yellow "Using isolated gcloud config: ${gcloud_config_dir}." + export CLOUDSDK_CONFIG="${gcloud_config_dir}" + + log_yellow "Using ${TRAMPOLINE_SERVICE_ACCOUNT} for authentication." + gcloud auth activate-service-account \ + --key-file "${TRAMPOLINE_SERVICE_ACCOUNT}" + log_yellow "Configuring Container Registry access" + gcloud auth configure-docker --quiet +fi + +required_envvars=( + # The basic trampoline configurations. + "TRAMPOLINE_IMAGE" + "TRAMPOLINE_BUILD_FILE" +) + +if [[ -f "${PROJECT_ROOT}/.trampolinerc" ]]; then + source "${PROJECT_ROOT}/.trampolinerc" +fi + +log_yellow "Checking environment variables." +for e in "${required_envvars[@]}" +do + if [[ -z "${!e:-}" ]]; then + log "Missing ${e} env var. Aborting." + exit 1 + fi +done + +# We want to support legacy style TRAMPOLINE_BUILD_FILE used with V1 +# script: e.g. "github/repo-name/.kokoro/run_tests.sh" +TRAMPOLINE_BUILD_FILE="${TRAMPOLINE_BUILD_FILE#github/*/}" +log_yellow "Using TRAMPOLINE_BUILD_FILE: ${TRAMPOLINE_BUILD_FILE}" + +# ignore error on docker operations and test execution +set +e + +log_yellow "Preparing Docker image." +# We only download the docker image in CI builds. +if [[ "${RUNNING_IN_CI:-}" == "true" ]]; then + # Download the docker image specified by `TRAMPOLINE_IMAGE` + + # We may want to add --max-concurrent-downloads flag. + + log_yellow "Start pulling the Docker image: ${TRAMPOLINE_IMAGE}." + if docker pull "${TRAMPOLINE_IMAGE}"; then + log_green "Finished pulling the Docker image: ${TRAMPOLINE_IMAGE}." + has_image="true" + else + log_red "Failed pulling the Docker image: ${TRAMPOLINE_IMAGE}." + has_image="false" + fi +else + # For local run, check if we have the image. + if docker images "${TRAMPOLINE_IMAGE}:latest" | grep "${TRAMPOLINE_IMAGE}"; then + has_image="true" + else + has_image="false" + fi +fi + + +# The default user for a Docker container has uid 0 (root). To avoid +# creating root-owned files in the build directory we tell docker to +# use the current user ID. +user_uid="$(id -u)" +user_gid="$(id -g)" +user_name="$(id -un)" + +# To allow docker in docker, we add the user to the docker group in +# the host os. +docker_gid=$(cut -d: -f3 < <(getent group docker)) + +update_cache="false" +if [[ "${TRAMPOLINE_DOCKERFILE:-none}" != "none" ]]; then + # Build the Docker image from the source. + context_dir=$(dirname "${TRAMPOLINE_DOCKERFILE}") + docker_build_flags=( + "-f" "${TRAMPOLINE_DOCKERFILE}" + "-t" "${TRAMPOLINE_IMAGE}" + "--build-arg" "UID=${user_uid}" + "--build-arg" "USERNAME=${user_name}" + ) + if [[ "${has_image}" == "true" ]]; then + docker_build_flags+=("--cache-from" "${TRAMPOLINE_IMAGE}") + fi + + log_yellow "Start building the docker image." + if [[ "${TRAMPOLINE_VERBOSE:-false}" == "true" ]]; then + echo "docker build" "${docker_build_flags[@]}" "${context_dir}" + fi + + # ON CI systems, we want to suppress docker build logs, only + # output the logs when it fails. + if [[ "${RUNNING_IN_CI:-}" == "true" ]]; then + if docker build "${docker_build_flags[@]}" "${context_dir}" \ + > "${tmpdir}/docker_build.log" 2>&1; then + if [[ "${TRAMPOLINE_VERBOSE:-}" == "true" ]]; then + cat "${tmpdir}/docker_build.log" + fi + + log_green "Finished building the docker image." + update_cache="true" + else + log_red "Failed to build the Docker image, aborting." + log_yellow "Dumping the build logs:" + cat "${tmpdir}/docker_build.log" + exit 1 + fi + else + if docker build "${docker_build_flags[@]}" "${context_dir}"; then + log_green "Finished building the docker image." + update_cache="true" + else + log_red "Failed to build the Docker image, aborting." + exit 1 + fi + fi +else + if [[ "${has_image}" != "true" ]]; then + log_red "We do not have ${TRAMPOLINE_IMAGE} locally, aborting." + exit 1 + fi +fi + +# We use an array for the flags so they are easier to document. +docker_flags=( + # Remove the container after it exists. + "--rm" + + # Use the host network. + "--network=host" + + # Run in priviledged mode. We are not using docker for sandboxing or + # isolation, just for packaging our dev tools. + "--privileged" + + # Run the docker script with the user id. Because the docker image gets to + # write in ${PWD} you typically want this to be your user id. + # To allow docker in docker, we need to use docker gid on the host. + "--user" "${user_uid}:${docker_gid}" + + # Pass down the USER. + "--env" "USER=${user_name}" + + # Mount the project directory inside the Docker container. + "--volume" "${PROJECT_ROOT}:${TRAMPOLINE_WORKSPACE}" + "--workdir" "${TRAMPOLINE_WORKSPACE}" + "--env" "PROJECT_ROOT=${TRAMPOLINE_WORKSPACE}" + + # Mount the temporary home directory. + "--volume" "${tmphome}:/h" + "--env" "HOME=/h" + + # Allow docker in docker. + "--volume" "/var/run/docker.sock:/var/run/docker.sock" + + # Mount the /tmp so that docker in docker can mount the files + # there correctly. + "--volume" "/tmp:/tmp" + # Pass down the KOKORO_GFILE_DIR and KOKORO_KEYSTORE_DIR + # TODO(tmatsuo): This part is not portable. + "--env" "TRAMPOLINE_SECRET_DIR=/secrets" + "--volume" "${KOKORO_GFILE_DIR:-/dev/shm}:/secrets/gfile" + "--env" "KOKORO_GFILE_DIR=/secrets/gfile" + "--volume" "${KOKORO_KEYSTORE_DIR:-/dev/shm}:/secrets/keystore" + "--env" "KOKORO_KEYSTORE_DIR=/secrets/keystore" +) + +# Add an option for nicer output if the build gets a tty. +if [[ -t 0 ]]; then + docker_flags+=("-it") +fi + +# Passing down env vars +for e in "${pass_down_envvars[@]}" +do + if [[ -n "${!e:-}" ]]; then + docker_flags+=("--env" "${e}=${!e}") + fi +done + +# If arguments are given, all arguments will become the commands run +# in the container, otherwise run TRAMPOLINE_BUILD_FILE. +if [[ $# -ge 1 ]]; then + log_yellow "Running the given commands '" "${@:1}" "' in the container." + readonly commands=("${@:1}") + if [[ "${TRAMPOLINE_VERBOSE:-}" == "true" ]]; then + echo docker run "${docker_flags[@]}" "${TRAMPOLINE_IMAGE}" "${commands[@]}" + fi + docker run "${docker_flags[@]}" "${TRAMPOLINE_IMAGE}" "${commands[@]}" +else + log_yellow "Running the tests in a Docker container." + docker_flags+=("--entrypoint=${TRAMPOLINE_BUILD_FILE}") + if [[ "${TRAMPOLINE_VERBOSE:-}" == "true" ]]; then + echo docker run "${docker_flags[@]}" "${TRAMPOLINE_IMAGE}" + fi + docker run "${docker_flags[@]}" "${TRAMPOLINE_IMAGE}" +fi + + +test_retval=$? + +if [[ ${test_retval} -eq 0 ]]; then + log_green "Build finished with ${test_retval}" +else + log_red "Build finished with ${test_retval}" +fi + +# Only upload it when the test passes. +if [[ "${update_cache}" == "true" ]] && \ + [[ $test_retval == 0 ]] && \ + [[ "${TRAMPOLINE_IMAGE_UPLOAD:-false}" == "true" ]]; then + log_yellow "Uploading the Docker image." + if docker push "${TRAMPOLINE_IMAGE}"; then + log_green "Finished uploading the Docker image." + else + log_red "Failed uploading the Docker image." + fi + # Call trampoline_after_upload_hook if it's defined. + if function_exists trampoline_after_upload_hook; then + trampoline_after_upload_hook + fi + +fi + +exit "${test_retval}" diff --git a/.trampolinerc b/.trampolinerc new file mode 100644 index 00000000..995ee291 --- /dev/null +++ b/.trampolinerc @@ -0,0 +1,51 @@ +# Copyright 2020 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. + +# Template for .trampolinerc + +# Add required env vars here. +required_envvars+=( + "STAGING_BUCKET" + "V2_STAGING_BUCKET" +) + +# Add env vars which are passed down into the container here. +pass_down_envvars+=( + "STAGING_BUCKET" + "V2_STAGING_BUCKET" +) + +# Prevent unintentional override on the default image. +if [[ "${TRAMPOLINE_IMAGE_UPLOAD:-false}" == "true" ]] && \ + [[ -z "${TRAMPOLINE_IMAGE:-}" ]]; then + echo "Please set TRAMPOLINE_IMAGE if you want to upload the Docker image." + exit 1 +fi + +# Define the default value if it makes sense. +if [[ -z "${TRAMPOLINE_IMAGE_UPLOAD:-}" ]]; then + TRAMPOLINE_IMAGE_UPLOAD="" +fi + +if [[ -z "${TRAMPOLINE_IMAGE:-}" ]]; then + TRAMPOLINE_IMAGE="" +fi + +if [[ -z "${TRAMPOLINE_DOCKERFILE:-}" ]]; then + TRAMPOLINE_DOCKERFILE="" +fi + +if [[ -z "${TRAMPOLINE_BUILD_FILE:-}" ]]; then + TRAMPOLINE_BUILD_FILE="" +fi diff --git a/docs/conf.py b/docs/conf.py index 475bfeb1..7341e8bd 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -20,12 +20,16 @@ # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath("..")) +# For plugins that can not read conf.py. +# See also: https://github.com/docascode/sphinx-docfx-yaml/issues/85 +sys.path.insert(0, os.path.abspath(".")) + __version__ = "" # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. -needs_sphinx = "1.6.3" +needs_sphinx = "1.5.5" # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom @@ -90,7 +94,12 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = ["_build"] +exclude_patterns = [ + "_build", + "samples/AUTHORING_GUIDE.md", + "samples/CONTRIBUTING.md", + "samples/snippets/README.rst", +] # The reST default role (used for this markup: `text`) to use for all # documents. diff --git a/docs/gapic/v1beta1/api.rst b/docs/gapic/v1beta1/api.rst index 5bf656fe..89fdb487 100644 --- a/docs/gapic/v1beta1/api.rst +++ b/docs/gapic/v1beta1/api.rst @@ -1,5 +1,5 @@ -Client for Cloud Security Command Center API -============================================ +Client for Security Command Center API +====================================== .. automodule:: google.cloud.securitycenter_v1beta1 :members: diff --git a/docs/gapic/v1beta1/types.rst b/docs/gapic/v1beta1/types.rst index 4af19d8c..1ec286a2 100644 --- a/docs/gapic/v1beta1/types.rst +++ b/docs/gapic/v1beta1/types.rst @@ -1,5 +1,5 @@ -Types for Cloud Security Command Center API Client -================================================== +Types for Security Command Center API Client +============================================ .. automodule:: google.cloud.securitycenter_v1beta1.types :members: \ No newline at end of file diff --git a/google/cloud/securitycenter_v1/__init__.py b/google/cloud/securitycenter_v1/__init__.py index 27c3ed04..e7f67b46 100644 --- a/google/cloud/securitycenter_v1/__init__.py +++ b/google/cloud/securitycenter_v1/__init__.py @@ -1,95 +1,45 @@ # -*- coding: utf-8 -*- - +# # Copyright 2020 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 +# 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. -# -from .services.security_center import SecurityCenterClient -from .types.asset import Asset -from .types.finding import Finding -from .types.notification_config import NotificationConfig -from .types.notification_message import NotificationMessage -from .types.organization_settings import OrganizationSettings -from .types.resource import Resource -from .types.run_asset_discovery_response import RunAssetDiscoveryResponse -from .types.security_marks import SecurityMarks -from .types.securitycenter_service import CreateFindingRequest -from .types.securitycenter_service import CreateNotificationConfigRequest -from .types.securitycenter_service import CreateSourceRequest -from .types.securitycenter_service import DeleteNotificationConfigRequest -from .types.securitycenter_service import GetNotificationConfigRequest -from .types.securitycenter_service import GetOrganizationSettingsRequest -from .types.securitycenter_service import GetSourceRequest -from .types.securitycenter_service import GroupAssetsRequest -from .types.securitycenter_service import GroupAssetsResponse -from .types.securitycenter_service import GroupFindingsRequest -from .types.securitycenter_service import GroupFindingsResponse -from .types.securitycenter_service import GroupResult -from .types.securitycenter_service import ListAssetsRequest -from .types.securitycenter_service import ListAssetsResponse -from .types.securitycenter_service import ListFindingsRequest -from .types.securitycenter_service import ListFindingsResponse -from .types.securitycenter_service import ListNotificationConfigsRequest -from .types.securitycenter_service import ListNotificationConfigsResponse -from .types.securitycenter_service import ListSourcesRequest -from .types.securitycenter_service import ListSourcesResponse -from .types.securitycenter_service import RunAssetDiscoveryRequest -from .types.securitycenter_service import SetFindingStateRequest -from .types.securitycenter_service import UpdateFindingRequest -from .types.securitycenter_service import UpdateNotificationConfigRequest -from .types.securitycenter_service import UpdateOrganizationSettingsRequest -from .types.securitycenter_service import UpdateSecurityMarksRequest -from .types.securitycenter_service import UpdateSourceRequest -from .types.source import Source + +from __future__ import absolute_import +import sys +import warnings + +from google.cloud.securitycenter_v1 import types +from google.cloud.securitycenter_v1.gapic import enums +from google.cloud.securitycenter_v1.gapic import security_center_client + + +if sys.version_info[:2] == (2, 7): + message = ( + "A future version of this library will drop support for Python 2.7. " + "More details about Python 2 support for Google Cloud Client Libraries " + "can be found at https://cloud.google.com/python/docs/python2-sunset/" + ) + warnings.warn(message, DeprecationWarning) + + +class SecurityCenterClient(security_center_client.SecurityCenterClient): + __doc__ = security_center_client.SecurityCenterClient.__doc__ + enums = enums __all__ = ( - "Asset", - "CreateFindingRequest", - "CreateNotificationConfigRequest", - "CreateSourceRequest", - "DeleteNotificationConfigRequest", - "Finding", - "GetNotificationConfigRequest", - "GetOrganizationSettingsRequest", - "GetSourceRequest", - "GroupAssetsRequest", - "GroupAssetsResponse", - "GroupFindingsRequest", - "GroupFindingsResponse", - "GroupResult", - "ListAssetsRequest", - "ListAssetsResponse", - "ListFindingsRequest", - "ListFindingsResponse", - "ListNotificationConfigsRequest", - "ListNotificationConfigsResponse", - "ListSourcesRequest", - "ListSourcesResponse", - "NotificationConfig", - "NotificationMessage", - "OrganizationSettings", - "Resource", - "RunAssetDiscoveryRequest", - "RunAssetDiscoveryResponse", - "SecurityMarks", - "SetFindingStateRequest", - "Source", - "UpdateFindingRequest", - "UpdateNotificationConfigRequest", - "UpdateOrganizationSettingsRequest", - "UpdateSecurityMarksRequest", - "UpdateSourceRequest", + "enums", + "types", "SecurityCenterClient", ) diff --git a/google/cloud/securitycenter_v1/gapic/security_center_client.py b/google/cloud/securitycenter_v1/gapic/security_center_client.py index 9c1f9104..e6c19fcd 100644 --- a/google/cloud/securitycenter_v1/gapic/security_center_client.py +++ b/google/cloud/securitycenter_v1/gapic/security_center_client.py @@ -282,35 +282,37 @@ def __init__( self._inner_api_calls = {} # Service calls - def get_iam_policy( + def create_source( self, - resource, - options_=None, + parent, + source, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ - Gets the access control policy on the specified Source. + Creates a source. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> - >>> # TODO: Initialize `resource`: - >>> resource = '' + >>> parent = client.organization_path('[ORGANIZATION]') >>> - >>> response = client.get_iam_policy(resource) + >>> # TODO: Initialize `source`: + >>> source = {} + >>> + >>> response = client.create_source(parent, source) Args: - resource (str): REQUIRED: The resource for which the policy is being requested. - See the operation documentation for the appropriate value for this field. - options_ (Union[dict, ~google.cloud.securitycenter_v1.types.GetPolicyOptions]): OPTIONAL: A ``GetPolicyOptions`` object for specifying options to - ``GetIamPolicy``. This field is only used by Cloud IAM. + parent (str): Required. Resource name of the new source's parent. Its format + should be "organizations/[organization_id]". + source (Union[dict, ~google.cloud.securitycenter_v1.types.Source]): Required. The Source being created, only the display_name and + description will be used. All other fields will be ignored. If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.GetPolicyOptions` + message :class:`~google.cloud.securitycenter_v1.types.Source` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -321,7 +323,7 @@ def get_iam_policy( that is provided to the method. Returns: - A :class:`~google.cloud.securitycenter_v1.types.Policy` instance. + A :class:`~google.cloud.securitycenter_v1.types.Source` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request @@ -331,24 +333,24 @@ def get_iam_policy( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "get_iam_policy" not in self._inner_api_calls: + if "create_source" not in self._inner_api_calls: self._inner_api_calls[ - "get_iam_policy" + "create_source" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_iam_policy, - default_retry=self._method_configs["GetIamPolicy"].retry, - default_timeout=self._method_configs["GetIamPolicy"].timeout, + self.transport.create_source, + default_retry=self._method_configs["CreateSource"].retry, + default_timeout=self._method_configs["CreateSource"].timeout, client_info=self._client_info, ) - request = iam_policy_pb2.GetIamPolicyRequest( - resource=resource, options=options_, + request = securitycenter_service_pb2.CreateSourceRequest( + parent=parent, source=source, ) if metadata is None: metadata = [] metadata = list(metadata) try: - routing_header = [("resource", resource)] + routing_header = [("parent", parent)] except AttributeError: pass else: @@ -357,186 +359,49 @@ def get_iam_policy( ) metadata.append(routing_metadata) - return self._inner_api_calls["get_iam_policy"]( + return self._inner_api_calls["create_source"]( request, retry=retry, timeout=timeout, metadata=metadata ) - def group_assets( + def create_finding( self, parent, - group_by, - filter_=None, - compare_duration=None, - read_time=None, - page_size=None, + finding_id, + finding, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ - Filters an organization's assets and groups them by their specified - properties. + Creates a finding. The corresponding source must exist for finding creation + to succeed. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> - >>> parent = client.organization_path('[ORGANIZATION]') - >>> - >>> # TODO: Initialize `group_by`: - >>> group_by = '' - >>> - >>> # Iterate over all results - >>> for element in client.group_assets(parent, group_by): - ... # process element - ... pass + >>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]') >>> + >>> # TODO: Initialize `finding_id`: + >>> finding_id = '' >>> - >>> # Alternatively: + >>> # TODO: Initialize `finding`: + >>> finding = {} >>> - >>> # Iterate over results one page at a time - >>> for page in client.group_assets(parent, group_by).pages: - ... for element in page: - ... # process element - ... pass + >>> response = client.create_finding(parent, finding_id, finding) Args: - parent (str): Required. Name of the organization to groupBy. Its format is - "organizations/[organization_id]". - group_by (str): Required. Expression that defines what assets fields to use for - grouping. The string value should follow SQL syntax: comma separated - list of fields. For example: - "security_center_properties.resource_project,security_center_properties.project". - - The following fields are supported when compare_duration is not set: - - - security_center_properties.resource_project - - security_center_properties.resource_project_display_name - - security_center_properties.resource_type - - security_center_properties.resource_parent - - security_center_properties.resource_parent_display_name - - The following fields are supported when compare_duration is set: - - - security_center_properties.resource_type - - security_center_properties.resource_project_display_name - - security_center_properties.resource_parent_display_name - filter_ (str): Expression that defines the filter to apply across assets. The - expression is a list of zero or more restrictions combined via logical - operators ``AND`` and ``OR``. Parentheses are supported, and ``OR`` has - higher precedence than ``AND``. - - Restrictions have the form `` `` and may have a - ``-`` character in front of them to indicate negation. The fields map to - those defined in the Asset resource. Examples include: - - - name - - security_center_properties.resource_name - - resource_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an RFC3339 string. - Examples: ``update_time = "2019-06-10T16:07:18-07:00"`` - ``update_time = 1560208038000`` - - - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an RFC3339 string. - Examples: ``create_time = "2019-06-10T16:07:18-07:00"`` - ``create_time = 1560208038000`` - - - iam_policy.policy_blob: ``=``, ``:`` - - - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, ``<=`` - - - security_marks.marks: ``=``, ``:`` - - - security_center_properties.resource_name: ``=``, ``:`` - - - security_center_properties.resource_display_name: ``=``, ``:`` - - - security_center_properties.resource_type: ``=``, ``:`` - - - security_center_properties.resource_parent: ``=``, ``:`` - - - security_center_properties.resource_parent_display_name: ``=``, ``:`` - - - security_center_properties.resource_project: ``=``, ``:`` - - - security_center_properties.resource_project_display_name: ``=``, - ``:`` - - - security_center_properties.resource_owners: ``=``, ``:`` - - For example, ``resource_properties.size = 100`` is a valid filter - string. - - Use a partial match on the empty string to filter based on a property - existing:\ ``resource_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter based on a - property not existing: ``-resource_properties.my_property : ""`` - compare_duration (Union[dict, ~google.cloud.securitycenter_v1.types.Duration]): When compare_duration is set, the GroupResult's "state_change" - property is updated to indicate whether the asset was added, removed, or - remained present during the compare_duration period of time that - precedes the read_time. This is the time between (read_time - - compare_duration) and read_time. - - The state change value is derived based on the presence of the asset at - the two points in time. Intermediate state changes between the two times - don't affect the result. For example, the results aren't affected if the - asset is removed and re-created again. - - Possible "state_change" values when compare_duration is specified: - - - "ADDED": indicates that the asset was not present at the start of - compare_duration, but present at reference_time. - - "REMOVED": indicates that the asset was present at the start of - compare_duration, but not present at reference_time. - - "ACTIVE": indicates that the asset was present at both the start and - the end of the time period defined by compare_duration and - reference_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set for all - assets present at read_time. - - If this field is set then ``state_change`` must be a specified field in - ``group_by``. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Duration` - read_time (Union[dict, ~google.cloud.securitycenter_v1.types.Timestamp]): Time used as a reference point when filtering assets. The filter is limited - to assets existing at the supplied time and their values are those at that - specific time. Absence of this field will default to the API's version of - NOW. + parent (str): Required. Resource name of the new finding's parent. Its format + should be "organizations/[organization_id]/sources/[source_id]". + finding_id (str): Required. Unique identifier provided by the client within the parent scope. + It must be alphanumeric and less than or equal to 32 characters and + greater than 0 characters in length. + finding (Union[dict, ~google.cloud.securitycenter_v1.types.Finding]): Required. The Finding being created. The name and security_marks + will be ignored as they are both output only fields on this resource. If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Timestamp` - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. + message :class:`~google.cloud.securitycenter_v1.types.Finding` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -547,10 +412,7 @@ def group_assets( that is provided to the method. Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.securitycenter_v1.types.GroupResult` instances. - You can also iterate over the pages of the response - using its `pages` property. + A :class:`~google.cloud.securitycenter_v1.types.Finding` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request @@ -560,23 +422,18 @@ def group_assets( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "group_assets" not in self._inner_api_calls: + if "create_finding" not in self._inner_api_calls: self._inner_api_calls[ - "group_assets" + "create_finding" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.group_assets, - default_retry=self._method_configs["GroupAssets"].retry, - default_timeout=self._method_configs["GroupAssets"].timeout, + self.transport.create_finding, + default_retry=self._method_configs["CreateFinding"].retry, + default_timeout=self._method_configs["CreateFinding"].timeout, client_info=self._client_info, ) - request = securitycenter_service_pb2.GroupAssetsRequest( - parent=parent, - group_by=group_by, - filter=filter_, - compare_duration=compare_duration, - read_time=read_time, - page_size=page_size, + request = securitycenter_service_pb2.CreateFindingRequest( + parent=parent, finding_id=finding_id, finding=finding, ) if metadata is None: metadata = [] @@ -591,187 +448,50 @@ def group_assets( ) metadata.append(routing_metadata) - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["group_assets"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="group_by_results", - request_token_field="page_token", - response_token_field="next_page_token", + return self._inner_api_calls["create_finding"]( + request, retry=retry, timeout=timeout, metadata=metadata ) - return iterator - def group_findings( + def create_notification_config( self, parent, - group_by, - filter_=None, - read_time=None, - compare_duration=None, - page_size=None, + config_id, + notification_config, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. Example: - /v1/organizations/{organization_id}/sources/-/findings + Creates a notification config. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> - >>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]') - >>> - >>> # TODO: Initialize `group_by`: - >>> group_by = '' - >>> - >>> # Iterate over all results - >>> for element in client.group_findings(parent, group_by): - ... # process element - ... pass + >>> parent = client.organization_path('[ORGANIZATION]') >>> + >>> # TODO: Initialize `config_id`: + >>> config_id = '' >>> - >>> # Alternatively: + >>> # TODO: Initialize `notification_config`: + >>> notification_config = {} >>> - >>> # Iterate over results one page at a time - >>> for page in client.group_findings(parent, group_by).pages: - ... for element in page: - ... # process element - ... pass + >>> response = client.create_notification_config(parent, config_id, notification_config) Args: - parent (str): Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]". To groupBy across - all sources provide a source_id of ``-``. For example: - organizations/{organization_id}/sources/- - group_by (str): Required. Expression that defines what assets fields to use for - grouping (including ``state_change``). The string value should follow - SQL syntax: comma separated list of fields. For example: - "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - - The following fields are supported when compare_duration is set: - - - state_change - filter_ (str): Expression that defines the filter to apply across findings. The - expression is a list of one or more restrictions combined via logical - operators ``AND`` and ``OR``. Parentheses are supported, and ``OR`` has - higher precedence than ``AND``. - - Restrictions have the form `` `` and may have a - ``-`` character in front of them to indicate negation. Examples include: - - - name - - source_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - parent: ``=``, ``:`` - - - resource_name: ``=``, ``:`` - - - state: ``=``, ``:`` - - - category: ``=``, ``:`` - - - external_uri: ``=``, ``:`` - - - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an RFC3339 string. - Examples: ``event_time = "2019-06-10T16:07:18-07:00"`` - ``event_time = 1560208038000`` - - - security_marks.marks: ``=``, ``:`` - - - source_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, ``<=`` - - For example, ``source_properties.size = 100`` is a valid filter string. - - Use a partial match on the empty string to filter based on a property - existing: ``source_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter based on a - property not existing: ``-source_properties.my_property : ""`` - read_time (Union[dict, ~google.cloud.securitycenter_v1.types.Timestamp]): Time used as a reference point when filtering findings. The filter is - limited to findings existing at the supplied time and their values are - those at that specific time. Absence of this field will default to the - API's version of NOW. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Timestamp` - compare_duration (Union[dict, ~google.cloud.securitycenter_v1.types.Duration]): When compare_duration is set, the GroupResult's "state_change" - attribute is updated to indicate whether the finding had its state - changed, the finding's state remained unchanged, or if the finding was - added during the compare_duration period of time that precedes the - read_time. This is the time between (read_time - compare_duration) and - read_time. - - The state_change value is derived based on the presence and state of the - finding at the two points in time. Intermediate state changes between - the two times don't affect the result. For example, the results aren't - affected if the finding is made inactive and then active again. - - Possible "state_change" values when compare_duration is specified: - - - "CHANGED": indicates that the finding was present and matched the - given filter at the start of compare_duration, but changed its state - at read_time. - - "UNCHANGED": indicates that the finding was present and matched the - given filter at the start of compare_duration and did not change - state at read_time. - - "ADDED": indicates that the finding did not match the given filter or - was not present at the start of compare_duration, but was present at - read_time. - - "REMOVED": indicates that the finding was present and matched the - filter at the start of compare_duration, but did not match the filter - at read_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set for all - findings present at read_time. - - If this field is set then ``state_change`` must be a specified field in - ``group_by``. + parent (str): Required. Resource name of the new notification config's parent. Its + format is "organizations/[organization_id]". + config_id (str): Required. + Unique identifier provided by the client within the parent scope. + It must be between 1 and 128 characters, and contains alphanumeric + characters, underscores or hyphens only. + notification_config (Union[dict, ~google.cloud.securitycenter_v1.types.NotificationConfig]): Required. The notification config being created. The name and the service + account will be ignored as they are both output only fields on this + resource. If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Duration` - page_size (int): The maximum number of resources contained in the - underlying API response. If page streaming is performed per- - resource, this parameter does not affect the return value. If page - streaming is performed per-page, this determines the maximum number - of resources in a page. + message :class:`~google.cloud.securitycenter_v1.types.NotificationConfig` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -782,10 +502,7 @@ def group_findings( that is provided to the method. Returns: - A :class:`~google.api_core.page_iterator.PageIterator` instance. - An iterable of :class:`~google.cloud.securitycenter_v1.types.GroupResult` instances. - You can also iterate over the pages of the response - using its `pages` property. + A :class:`~google.cloud.securitycenter_v1.types.NotificationConfig` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request @@ -795,23 +512,20 @@ def group_findings( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "group_findings" not in self._inner_api_calls: + if "create_notification_config" not in self._inner_api_calls: self._inner_api_calls[ - "group_findings" + "create_notification_config" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.group_findings, - default_retry=self._method_configs["GroupFindings"].retry, - default_timeout=self._method_configs["GroupFindings"].timeout, + self.transport.create_notification_config, + default_retry=self._method_configs["CreateNotificationConfig"].retry, + default_timeout=self._method_configs[ + "CreateNotificationConfig" + ].timeout, client_info=self._client_info, ) - request = securitycenter_service_pb2.GroupFindingsRequest( - parent=parent, - group_by=group_by, - filter=filter_, - read_time=read_time, - compare_duration=compare_duration, - page_size=page_size, + request = securitycenter_service_pb2.CreateNotificationConfigRequest( + parent=parent, config_id=config_id, notification_config=notification_config, ) if metadata is None: metadata = [] @@ -826,52 +540,32 @@ def group_findings( ) metadata.append(routing_metadata) - iterator = google.api_core.page_iterator.GRPCIterator( - client=None, - method=functools.partial( - self._inner_api_calls["group_findings"], - retry=retry, - timeout=timeout, - metadata=metadata, - ), - request=request, - items_field="group_by_results", - request_token_field="page_token", - response_token_field="next_page_token", + return self._inner_api_calls["create_notification_config"]( + request, retry=retry, timeout=timeout, metadata=metadata ) - return iterator - def test_iam_permissions( + def delete_notification_config( self, - resource, - permissions, + name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ - Returns the permissions that a caller has on the specified source. + Deletes a notification config. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> - >>> # TODO: Initialize `resource`: - >>> resource = '' - >>> - >>> # TODO: Initialize `permissions`: - >>> permissions = [] + >>> name = client.notification_config_path('[ORGANIZATION]', '[NOTIFICATION_CONFIG]') >>> - >>> response = client.test_iam_permissions(resource, permissions) + >>> client.delete_notification_config(name) Args: - resource (str): REQUIRED: The resource for which the policy detail is being requested. - See the operation documentation for the appropriate value for this field. - permissions (list[str]): The set of permissions to check for the ``resource``. Permissions - with wildcards (such as '*' or 'storage.*') are not allowed. For more - information see `IAM - Overview `__. + name (str): Required. Name of the notification config to delete. Its format is + "organizations/[organization_id]/notificationConfigs/[config_id]". retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -881,9 +575,6 @@ def test_iam_permissions( metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. - Returns: - A :class:`~google.cloud.securitycenter_v1.types.TestIamPermissionsResponse` instance. - Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. @@ -892,24 +583,24 @@ def test_iam_permissions( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "test_iam_permissions" not in self._inner_api_calls: + if "delete_notification_config" not in self._inner_api_calls: self._inner_api_calls[ - "test_iam_permissions" + "delete_notification_config" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.test_iam_permissions, - default_retry=self._method_configs["TestIamPermissions"].retry, - default_timeout=self._method_configs["TestIamPermissions"].timeout, + self.transport.delete_notification_config, + default_retry=self._method_configs["DeleteNotificationConfig"].retry, + default_timeout=self._method_configs[ + "DeleteNotificationConfig" + ].timeout, client_info=self._client_info, ) - request = iam_policy_pb2.TestIamPermissionsRequest( - resource=resource, permissions=permissions, - ) + request = securitycenter_service_pb2.DeleteNotificationConfigRequest(name=name,) if metadata is None: metadata = [] metadata = list(metadata) try: - routing_header = [("resource", resource)] + routing_header = [("name", name)] except AttributeError: pass else: @@ -918,41 +609,39 @@ def test_iam_permissions( ) metadata.append(routing_metadata) - return self._inner_api_calls["test_iam_permissions"]( + self._inner_api_calls["delete_notification_config"]( request, retry=retry, timeout=timeout, metadata=metadata ) - def create_source( + def get_iam_policy( self, - parent, - source, + resource, + options_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ - Creates a source. + Gets the access control policy on the specified Source. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> - >>> parent = client.organization_path('[ORGANIZATION]') - >>> - >>> # TODO: Initialize `source`: - >>> source = {} + >>> # TODO: Initialize `resource`: + >>> resource = '' >>> - >>> response = client.create_source(parent, source) + >>> response = client.get_iam_policy(resource) Args: - parent (str): Required. Resource name of the new source's parent. Its format - should be "organizations/[organization_id]". - source (Union[dict, ~google.cloud.securitycenter_v1.types.Source]): Required. The Source being created, only the display_name and - description will be used. All other fields will be ignored. + resource (str): REQUIRED: The resource for which the policy is being requested. + See the operation documentation for the appropriate value for this field. + options_ (Union[dict, ~google.cloud.securitycenter_v1.types.GetPolicyOptions]): OPTIONAL: A ``GetPolicyOptions`` object for specifying options to + ``GetIamPolicy``. This field is only used by Cloud IAM. If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Source` + message :class:`~google.cloud.securitycenter_v1.types.GetPolicyOptions` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -963,7 +652,7 @@ def create_source( that is provided to the method. Returns: - A :class:`~google.cloud.securitycenter_v1.types.Source` instance. + A :class:`~google.cloud.securitycenter_v1.types.Policy` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request @@ -973,24 +662,24 @@ def create_source( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "create_source" not in self._inner_api_calls: + if "get_iam_policy" not in self._inner_api_calls: self._inner_api_calls[ - "create_source" + "get_iam_policy" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_source, - default_retry=self._method_configs["CreateSource"].retry, - default_timeout=self._method_configs["CreateSource"].timeout, + self.transport.get_iam_policy, + default_retry=self._method_configs["GetIamPolicy"].retry, + default_timeout=self._method_configs["GetIamPolicy"].timeout, client_info=self._client_info, ) - request = securitycenter_service_pb2.CreateSourceRequest( - parent=parent, source=source, + request = iam_policy_pb2.GetIamPolicyRequest( + resource=resource, options=options_, ) if metadata is None: metadata = [] metadata = list(metadata) try: - routing_header = [("parent", parent)] + routing_header = [("resource", resource)] except AttributeError: pass else: @@ -999,49 +688,32 @@ def create_source( ) metadata.append(routing_metadata) - return self._inner_api_calls["create_source"]( + return self._inner_api_calls["get_iam_policy"]( request, retry=retry, timeout=timeout, metadata=metadata ) - def create_finding( + def get_notification_config( self, - parent, - finding_id, - finding, + name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ - Creates a finding. The corresponding source must exist for finding creation - to succeed. + Gets a notification config. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> - >>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]') - >>> - >>> # TODO: Initialize `finding_id`: - >>> finding_id = '' - >>> - >>> # TODO: Initialize `finding`: - >>> finding = {} + >>> name = client.notification_config_path('[ORGANIZATION]', '[NOTIFICATION_CONFIG]') >>> - >>> response = client.create_finding(parent, finding_id, finding) + >>> response = client.get_notification_config(name) Args: - parent (str): Required. Resource name of the new finding's parent. Its format - should be "organizations/[organization_id]/sources/[source_id]". - finding_id (str): Required. Unique identifier provided by the client within the parent scope. - It must be alphanumeric and less than or equal to 32 characters and - greater than 0 characters in length. - finding (Union[dict, ~google.cloud.securitycenter_v1.types.Finding]): Required. The Finding being created. The name and security_marks - will be ignored as they are both output only fields on this resource. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.Finding` + name (str): Required. Name of the notification config to get. Its format is + "organizations/[organization_id]/notificationConfigs/[config_id]". retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -1052,7 +724,7 @@ def create_finding( that is provided to the method. Returns: - A :class:`~google.cloud.securitycenter_v1.types.Finding` instance. + A :class:`~google.cloud.securitycenter_v1.types.NotificationConfig` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request @@ -1062,24 +734,22 @@ def create_finding( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "create_finding" not in self._inner_api_calls: + if "get_notification_config" not in self._inner_api_calls: self._inner_api_calls[ - "create_finding" + "get_notification_config" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_finding, - default_retry=self._method_configs["CreateFinding"].retry, - default_timeout=self._method_configs["CreateFinding"].timeout, + self.transport.get_notification_config, + default_retry=self._method_configs["GetNotificationConfig"].retry, + default_timeout=self._method_configs["GetNotificationConfig"].timeout, client_info=self._client_info, ) - request = securitycenter_service_pb2.CreateFindingRequest( - parent=parent, finding_id=finding_id, finding=finding, - ) + request = securitycenter_service_pb2.GetNotificationConfigRequest(name=name,) if metadata is None: metadata = [] metadata = list(metadata) try: - routing_header = [("parent", parent)] + routing_header = [("name", name)] except AttributeError: pass else: @@ -1088,50 +758,32 @@ def create_finding( ) metadata.append(routing_metadata) - return self._inner_api_calls["create_finding"]( + return self._inner_api_calls["get_notification_config"]( request, retry=retry, timeout=timeout, metadata=metadata ) - def create_notification_config( + def get_organization_settings( self, - parent, - config_id, - notification_config, + name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ - Creates a notification config. + Gets the settings for an organization. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> - >>> parent = client.organization_path('[ORGANIZATION]') - >>> - >>> # TODO: Initialize `config_id`: - >>> config_id = '' - >>> - >>> # TODO: Initialize `notification_config`: - >>> notification_config = {} + >>> name = client.organization_settings_path('[ORGANIZATION]') >>> - >>> response = client.create_notification_config(parent, config_id, notification_config) + >>> response = client.get_organization_settings(name) Args: - parent (str): Required. Resource name of the new notification config's parent. Its - format is "organizations/[organization_id]". - config_id (str): Required. - Unique identifier provided by the client within the parent scope. - It must be between 1 and 128 characters, and contains alphanumeric - characters, underscores or hyphens only. - notification_config (Union[dict, ~google.cloud.securitycenter_v1.types.NotificationConfig]): Required. The notification config being created. The name and the service - account will be ignored as they are both output only fields on this - resource. - - If a dict is provided, it must be of the same form as the protobuf - message :class:`~google.cloud.securitycenter_v1.types.NotificationConfig` + name (str): Required. Name of the organization to get organization settings for. + Its format is "organizations/[organization_id]/organizationSettings". retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -1142,7 +794,7 @@ def create_notification_config( that is provided to the method. Returns: - A :class:`~google.cloud.securitycenter_v1.types.NotificationConfig` instance. + A :class:`~google.cloud.securitycenter_v1.types.OrganizationSettings` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request @@ -1152,26 +804,22 @@ def create_notification_config( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "create_notification_config" not in self._inner_api_calls: + if "get_organization_settings" not in self._inner_api_calls: self._inner_api_calls[ - "create_notification_config" + "get_organization_settings" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.create_notification_config, - default_retry=self._method_configs["CreateNotificationConfig"].retry, - default_timeout=self._method_configs[ - "CreateNotificationConfig" - ].timeout, + self.transport.get_organization_settings, + default_retry=self._method_configs["GetOrganizationSettings"].retry, + default_timeout=self._method_configs["GetOrganizationSettings"].timeout, client_info=self._client_info, ) - request = securitycenter_service_pb2.CreateNotificationConfigRequest( - parent=parent, config_id=config_id, notification_config=notification_config, - ) + request = securitycenter_service_pb2.GetOrganizationSettingsRequest(name=name,) if metadata is None: metadata = [] metadata = list(metadata) try: - routing_header = [("parent", parent)] + routing_header = [("name", name)] except AttributeError: pass else: @@ -1180,11 +828,11 @@ def create_notification_config( ) metadata.append(routing_metadata) - return self._inner_api_calls["create_notification_config"]( + return self._inner_api_calls["get_organization_settings"]( request, retry=retry, timeout=timeout, metadata=metadata ) - def delete_notification_config( + def get_source( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, @@ -1192,20 +840,20 @@ def delete_notification_config( metadata=None, ): """ - Deletes a notification config. + Gets a source. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> - >>> name = client.notification_config_path('[ORGANIZATION]', '[NOTIFICATION_CONFIG]') + >>> name = client.source_path('[ORGANIZATION]', '[SOURCE]') >>> - >>> client.delete_notification_config(name) + >>> response = client.get_source(name) Args: - name (str): Required. Name of the notification config to delete. Its format is - "organizations/[organization_id]/notificationConfigs/[config_id]". + name (str): Required. Relative resource name of the source. Its format is + "organizations/[organization_id]/source/[source_id]". retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -1215,6 +863,9 @@ def delete_notification_config( metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. + Returns: + A :class:`~google.cloud.securitycenter_v1.types.Source` instance. + Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. @@ -1223,19 +874,17 @@ def delete_notification_config( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "delete_notification_config" not in self._inner_api_calls: + if "get_source" not in self._inner_api_calls: self._inner_api_calls[ - "delete_notification_config" + "get_source" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.delete_notification_config, - default_retry=self._method_configs["DeleteNotificationConfig"].retry, - default_timeout=self._method_configs[ - "DeleteNotificationConfig" - ].timeout, + self.transport.get_source, + default_retry=self._method_configs["GetSource"].retry, + default_timeout=self._method_configs["GetSource"].timeout, client_info=self._client_info, ) - request = securitycenter_service_pb2.DeleteNotificationConfigRequest(name=name,) + request = securitycenter_service_pb2.GetSourceRequest(name=name,) if metadata is None: metadata = [] metadata = list(metadata) @@ -1249,32 +898,186 @@ def delete_notification_config( ) metadata.append(routing_metadata) - self._inner_api_calls["delete_notification_config"]( + return self._inner_api_calls["get_source"]( request, retry=retry, timeout=timeout, metadata=metadata ) - def get_notification_config( + def group_assets( self, - name, + parent, + group_by, + filter_=None, + compare_duration=None, + read_time=None, + page_size=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ - Gets a notification config. + Filters an organization's assets and groups them by their specified + properties. Example: >>> from google.cloud import securitycenter_v1 >>> >>> client = securitycenter_v1.SecurityCenterClient() >>> - >>> name = client.notification_config_path('[ORGANIZATION]', '[NOTIFICATION_CONFIG]') + >>> parent = client.organization_path('[ORGANIZATION]') >>> - >>> response = client.get_notification_config(name) + >>> # TODO: Initialize `group_by`: + >>> group_by = '' + >>> + >>> # Iterate over all results + >>> for element in client.group_assets(parent, group_by): + ... # process element + ... pass + >>> + >>> + >>> # Alternatively: + >>> + >>> # Iterate over results one page at a time + >>> for page in client.group_assets(parent, group_by).pages: + ... for element in page: + ... # process element + ... pass Args: - name (str): Required. Name of the notification config to get. Its format is - "organizations/[organization_id]/notificationConfigs/[config_id]". + parent (str): Required. Name of the organization to groupBy. Its format is + "organizations/[organization_id]". + group_by (str): Required. Expression that defines what assets fields to use for + grouping. The string value should follow SQL syntax: comma separated + list of fields. For example: + "security_center_properties.resource_project,security_center_properties.project". + + The following fields are supported when compare_duration is not set: + + - security_center_properties.resource_project + - security_center_properties.resource_project_display_name + - security_center_properties.resource_type + - security_center_properties.resource_parent + - security_center_properties.resource_parent_display_name + + The following fields are supported when compare_duration is set: + + - security_center_properties.resource_type + - security_center_properties.resource_project_display_name + - security_center_properties.resource_parent_display_name + filter_ (str): Expression that defines the filter to apply across assets. The + expression is a list of zero or more restrictions combined via logical + operators ``AND`` and ``OR``. Parentheses are supported, and ``OR`` has + higher precedence than ``AND``. + + Restrictions have the form `` `` and may have a + ``-`` character in front of them to indicate negation. The fields map to + those defined in the Asset resource. Examples include: + + - name + - security_center_properties.resource_name + - resource_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an RFC3339 string. + Examples: ``update_time = "2019-06-10T16:07:18-07:00"`` + ``update_time = 1560208038000`` + + - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an RFC3339 string. + Examples: ``create_time = "2019-06-10T16:07:18-07:00"`` + ``create_time = 1560208038000`` + + - iam_policy.policy_blob: ``=``, ``:`` + + - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, ``<=`` + + - security_marks.marks: ``=``, ``:`` + + - security_center_properties.resource_name: ``=``, ``:`` + + - security_center_properties.resource_display_name: ``=``, ``:`` + + - security_center_properties.resource_type: ``=``, ``:`` + + - security_center_properties.resource_parent: ``=``, ``:`` + + - security_center_properties.resource_parent_display_name: ``=``, ``:`` + + - security_center_properties.resource_project: ``=``, ``:`` + + - security_center_properties.resource_project_display_name: ``=``, + ``:`` + + - security_center_properties.resource_owners: ``=``, ``:`` + + For example, ``resource_properties.size = 100`` is a valid filter + string. + + Use a partial match on the empty string to filter based on a property + existing:\ ``resource_properties.my_property : ""`` + + Use a negated partial match on the empty string to filter based on a + property not existing: ``-resource_properties.my_property : ""`` + compare_duration (Union[dict, ~google.cloud.securitycenter_v1.types.Duration]): When compare_duration is set, the GroupResult's "state_change" + property is updated to indicate whether the asset was added, removed, or + remained present during the compare_duration period of time that + precedes the read_time. This is the time between (read_time - + compare_duration) and read_time. + + The state change value is derived based on the presence of the asset at + the two points in time. Intermediate state changes between the two times + don't affect the result. For example, the results aren't affected if the + asset is removed and re-created again. + + Possible "state_change" values when compare_duration is specified: + + - "ADDED": indicates that the asset was not present at the start of + compare_duration, but present at reference_time. + - "REMOVED": indicates that the asset was present at the start of + compare_duration, but not present at reference_time. + - "ACTIVE": indicates that the asset was present at both the start and + the end of the time period defined by compare_duration and + reference_time. + + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set for all + assets present at read_time. + + If this field is set then ``state_change`` must be a specified field in + ``group_by``. + + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.securitycenter_v1.types.Duration` + read_time (Union[dict, ~google.cloud.securitycenter_v1.types.Timestamp]): Time used as a reference point when filtering assets. The filter is limited + to assets existing at the supplied time and their values are those at that + specific time. Absence of this field will default to the API's version of + NOW. + + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.securitycenter_v1.types.Timestamp` + page_size (int): The maximum number of resources contained in the + underlying API response. If page streaming is performed per- + resource, this parameter does not affect the return value. If page + streaming is performed per-page, this determines the maximum number + of resources in a page. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -1285,7 +1088,10 @@ def get_notification_config( that is provided to the method. Returns: - A :class:`~google.cloud.securitycenter_v1.types.NotificationConfig` instance. + A :class:`~google.api_core.page_iterator.PageIterator` instance. + An iterable of :class:`~google.cloud.securitycenter_v1.types.GroupResult` instances. + You can also iterate over the pages of the response + using its `pages` property. Raises: google.api_core.exceptions.GoogleAPICallError: If the request @@ -1295,22 +1101,29 @@ def get_notification_config( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "get_notification_config" not in self._inner_api_calls: + if "group_assets" not in self._inner_api_calls: self._inner_api_calls[ - "get_notification_config" + "group_assets" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_notification_config, - default_retry=self._method_configs["GetNotificationConfig"].retry, - default_timeout=self._method_configs["GetNotificationConfig"].timeout, + self.transport.group_assets, + default_retry=self._method_configs["GroupAssets"].retry, + default_timeout=self._method_configs["GroupAssets"].timeout, client_info=self._client_info, ) - request = securitycenter_service_pb2.GetNotificationConfigRequest(name=name,) + request = securitycenter_service_pb2.GroupAssetsRequest( + parent=parent, + group_by=group_by, + filter=filter_, + compare_duration=compare_duration, + read_time=read_time, + page_size=page_size, + ) if metadata is None: metadata = [] metadata = list(metadata) try: - routing_header = [("name", name)] + routing_header = [("parent", parent)] except AttributeError: pass else: @@ -1319,102 +1132,187 @@ def get_notification_config( ) metadata.append(routing_metadata) - return self._inner_api_calls["get_notification_config"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) + iterator = google.api_core.page_iterator.GRPCIterator( + client=None, + method=functools.partial( + self._inner_api_calls["group_assets"], + retry=retry, + timeout=timeout, + metadata=metadata, + ), + request=request, + items_field="group_by_results", + request_token_field="page_token", + response_token_field="next_page_token", + ) + return iterator + + def group_findings( + self, + parent, + group_by, + filter_=None, + read_time=None, + compare_duration=None, + page_size=None, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT, + metadata=None, + ): + """ + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. Example: + /v1/organizations/{organization_id}/sources/-/findings + + Example: + >>> from google.cloud import securitycenter_v1 + >>> + >>> client = securitycenter_v1.SecurityCenterClient() + >>> + >>> parent = client.source_path('[ORGANIZATION]', '[SOURCE]') + >>> + >>> # TODO: Initialize `group_by`: + >>> group_by = '' + >>> + >>> # Iterate over all results + >>> for element in client.group_findings(parent, group_by): + ... # process element + ... pass + >>> + >>> + >>> # Alternatively: + >>> + >>> # Iterate over results one page at a time + >>> for page in client.group_findings(parent, group_by).pages: + ... for element in page: + ... # process element + ... pass + + Args: + parent (str): Required. Name of the source to groupBy. Its format is + "organizations/[organization_id]/sources/[source_id]". To groupBy across + all sources provide a source_id of ``-``. For example: + organizations/{organization_id}/sources/- + group_by (str): Required. Expression that defines what assets fields to use for + grouping (including ``state_change``). The string value should follow + SQL syntax: comma separated list of fields. For example: + "parent,resource_name". + + The following fields are supported: + + - resource_name + - category + - state + - parent + + The following fields are supported when compare_duration is set: + + - state_change + filter_ (str): Expression that defines the filter to apply across findings. The + expression is a list of one or more restrictions combined via logical + operators ``AND`` and ``OR``. Parentheses are supported, and ``OR`` has + higher precedence than ``AND``. + + Restrictions have the form `` `` and may have a + ``-`` character in front of them to indicate negation. Examples include: + + - name + - source_properties.a_property + - security_marks.marks.marka + + The supported operators are: + + - ``=`` for all value types. + - ``>``, ``<``, ``>=``, ``<=`` for integer values. + - ``:``, meaning substring matching, for strings. + + The supported value types are: + + - string literals in quotes. + - integer literals without quotes. + - boolean literals ``true`` and ``false`` without quotes. + + The following field and operator combinations are supported: + + - name: ``=`` + + - parent: ``=``, ``:`` + + - resource_name: ``=``, ``:`` + + - state: ``=``, ``:`` + + - category: ``=``, ``:`` + + - external_uri: ``=``, ``:`` + + - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` + + Usage: This should be milliseconds since epoch or an RFC3339 string. + Examples: ``event_time = "2019-06-10T16:07:18-07:00"`` + ``event_time = 1560208038000`` + + - security_marks.marks: ``=``, ``:`` + + - source_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, ``<=`` - def get_organization_settings( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets the settings for an organization. + For example, ``source_properties.size = 100`` is a valid filter string. - Example: - >>> from google.cloud import securitycenter_v1 - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> name = client.organization_settings_path('[ORGANIZATION]') - >>> - >>> response = client.get_organization_settings(name) + Use a partial match on the empty string to filter based on a property + existing: ``source_properties.my_property : ""`` - Args: - name (str): Required. Name of the organization to get organization settings for. - Its format is "organizations/[organization_id]/organizationSettings". - retry (Optional[google.api_core.retry.Retry]): A retry object used - to retry requests. If ``None`` is specified, requests will - be retried using a default configuration. - timeout (Optional[float]): The amount of time, in seconds, to wait - for the request to complete. Note that if ``retry`` is - specified, the timeout applies to each individual attempt. - metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata - that is provided to the method. + Use a negated partial match on the empty string to filter based on a + property not existing: ``-source_properties.my_property : ""`` + read_time (Union[dict, ~google.cloud.securitycenter_v1.types.Timestamp]): Time used as a reference point when filtering findings. The filter is + limited to findings existing at the supplied time and their values are + those at that specific time. Absence of this field will default to the + API's version of NOW. - Returns: - A :class:`~google.cloud.securitycenter_v1.types.OrganizationSettings` instance. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.securitycenter_v1.types.Timestamp` + compare_duration (Union[dict, ~google.cloud.securitycenter_v1.types.Duration]): When compare_duration is set, the GroupResult's "state_change" + attribute is updated to indicate whether the finding had its state + changed, the finding's state remained unchanged, or if the finding was + added during the compare_duration period of time that precedes the + read_time. This is the time between (read_time - compare_duration) and + read_time. - Raises: - google.api_core.exceptions.GoogleAPICallError: If the request - failed for any reason. - google.api_core.exceptions.RetryError: If the request failed due - to a retryable error and retry attempts failed. - ValueError: If the parameters are invalid. - """ - # Wrap the transport method to add retry and timeout logic. - if "get_organization_settings" not in self._inner_api_calls: - self._inner_api_calls[ - "get_organization_settings" - ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_organization_settings, - default_retry=self._method_configs["GetOrganizationSettings"].retry, - default_timeout=self._method_configs["GetOrganizationSettings"].timeout, - client_info=self._client_info, - ) + The state_change value is derived based on the presence and state of the + finding at the two points in time. Intermediate state changes between + the two times don't affect the result. For example, the results aren't + affected if the finding is made inactive and then active again. - request = securitycenter_service_pb2.GetOrganizationSettingsRequest(name=name,) - if metadata is None: - metadata = [] - metadata = list(metadata) - try: - routing_header = [("name", name)] - except AttributeError: - pass - else: - routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( - routing_header - ) - metadata.append(routing_metadata) + Possible "state_change" values when compare_duration is specified: - return self._inner_api_calls["get_organization_settings"]( - request, retry=retry, timeout=timeout, metadata=metadata - ) + - "CHANGED": indicates that the finding was present and matched the + given filter at the start of compare_duration, but changed its state + at read_time. + - "UNCHANGED": indicates that the finding was present and matched the + given filter at the start of compare_duration and did not change + state at read_time. + - "ADDED": indicates that the finding did not match the given filter or + was not present at the start of compare_duration, but was present at + read_time. + - "REMOVED": indicates that the finding was present and matched the + filter at the start of compare_duration, but did not match the filter + at read_time. - def get_source( - self, - name, - retry=google.api_core.gapic_v1.method.DEFAULT, - timeout=google.api_core.gapic_v1.method.DEFAULT, - metadata=None, - ): - """ - Gets a source. + If compare_duration is not specified, then the only possible + state_change is "UNUSED", which will be the state_change set for all + findings present at read_time. - Example: - >>> from google.cloud import securitycenter_v1 - >>> - >>> client = securitycenter_v1.SecurityCenterClient() - >>> - >>> name = client.source_path('[ORGANIZATION]', '[SOURCE]') - >>> - >>> response = client.get_source(name) + If this field is set then ``state_change`` must be a specified field in + ``group_by``. - Args: - name (str): Required. Relative resource name of the source. Its format is - "organizations/[organization_id]/source/[source_id]". + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.securitycenter_v1.types.Duration` + page_size (int): The maximum number of resources contained in the + underlying API response. If page streaming is performed per- + resource, this parameter does not affect the return value. If page + streaming is performed per-page, this determines the maximum number + of resources in a page. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. @@ -1425,7 +1323,10 @@ def get_source( that is provided to the method. Returns: - A :class:`~google.cloud.securitycenter_v1.types.Source` instance. + A :class:`~google.api_core.page_iterator.PageIterator` instance. + An iterable of :class:`~google.cloud.securitycenter_v1.types.GroupResult` instances. + You can also iterate over the pages of the response + using its `pages` property. Raises: google.api_core.exceptions.GoogleAPICallError: If the request @@ -1435,22 +1336,29 @@ def get_source( ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. - if "get_source" not in self._inner_api_calls: + if "group_findings" not in self._inner_api_calls: self._inner_api_calls[ - "get_source" + "group_findings" ] = google.api_core.gapic_v1.method.wrap_method( - self.transport.get_source, - default_retry=self._method_configs["GetSource"].retry, - default_timeout=self._method_configs["GetSource"].timeout, + self.transport.group_findings, + default_retry=self._method_configs["GroupFindings"].retry, + default_timeout=self._method_configs["GroupFindings"].timeout, client_info=self._client_info, ) - request = securitycenter_service_pb2.GetSourceRequest(name=name,) + request = securitycenter_service_pb2.GroupFindingsRequest( + parent=parent, + group_by=group_by, + filter=filter_, + read_time=read_time, + compare_duration=compare_duration, + page_size=page_size, + ) if metadata is None: metadata = [] metadata = list(metadata) try: - routing_header = [("name", name)] + routing_header = [("parent", parent)] except AttributeError: pass else: @@ -1459,9 +1367,20 @@ def get_source( ) metadata.append(routing_metadata) - return self._inner_api_calls["get_source"]( - request, retry=retry, timeout=timeout, metadata=metadata + iterator = google.api_core.page_iterator.GRPCIterator( + client=None, + method=functools.partial( + self._inner_api_calls["group_findings"], + retry=retry, + timeout=timeout, + metadata=metadata, + ), + request=request, + items_field="group_by_results", + request_token_field="page_token", + response_token_field="next_page_token", ) + return iterator def list_assets( self, @@ -2394,6 +2313,87 @@ def set_iam_policy( request, retry=retry, timeout=timeout, metadata=metadata ) + def test_iam_permissions( + self, + resource, + permissions, + retry=google.api_core.gapic_v1.method.DEFAULT, + timeout=google.api_core.gapic_v1.method.DEFAULT, + metadata=None, + ): + """ + Returns the permissions that a caller has on the specified source. + + Example: + >>> from google.cloud import securitycenter_v1 + >>> + >>> client = securitycenter_v1.SecurityCenterClient() + >>> + >>> # TODO: Initialize `resource`: + >>> resource = '' + >>> + >>> # TODO: Initialize `permissions`: + >>> permissions = [] + >>> + >>> response = client.test_iam_permissions(resource, permissions) + + Args: + resource (str): REQUIRED: The resource for which the policy detail is being requested. + See the operation documentation for the appropriate value for this field. + permissions (list[str]): The set of permissions to check for the ``resource``. Permissions + with wildcards (such as '*' or 'storage.*') are not allowed. For more + information see `IAM + Overview `__. + retry (Optional[google.api_core.retry.Retry]): A retry object used + to retry requests. If ``None`` is specified, requests will + be retried using a default configuration. + timeout (Optional[float]): The amount of time, in seconds, to wait + for the request to complete. Note that if ``retry`` is + specified, the timeout applies to each individual attempt. + metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata + that is provided to the method. + + Returns: + A :class:`~google.cloud.securitycenter_v1.types.TestIamPermissionsResponse` instance. + + Raises: + google.api_core.exceptions.GoogleAPICallError: If the request + failed for any reason. + google.api_core.exceptions.RetryError: If the request failed due + to a retryable error and retry attempts failed. + ValueError: If the parameters are invalid. + """ + # Wrap the transport method to add retry and timeout logic. + if "test_iam_permissions" not in self._inner_api_calls: + self._inner_api_calls[ + "test_iam_permissions" + ] = google.api_core.gapic_v1.method.wrap_method( + self.transport.test_iam_permissions, + default_retry=self._method_configs["TestIamPermissions"].retry, + default_timeout=self._method_configs["TestIamPermissions"].timeout, + client_info=self._client_info, + ) + + request = iam_policy_pb2.TestIamPermissionsRequest( + resource=resource, permissions=permissions, + ) + if metadata is None: + metadata = [] + metadata = list(metadata) + try: + routing_header = [("resource", resource)] + except AttributeError: + pass + else: + routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( + routing_header + ) + metadata.append(routing_metadata) + + return self._inner_api_calls["test_iam_permissions"]( + request, retry=retry, timeout=timeout, metadata=metadata + ) + def update_finding( self, finding, diff --git a/google/cloud/securitycenter_v1/gapic/security_center_client_config.py b/google/cloud/securitycenter_v1/gapic/security_center_client_config.py index 7bf5a897..111431ea 100644 --- a/google/cloud/securitycenter_v1/gapic/security_center_client_config.py +++ b/google/cloud/securitycenter_v1/gapic/security_center_client_config.py @@ -2,135 +2,174 @@ "interfaces": { "google.cloud.securitycenter.v1.SecurityCenter": { "retry_codes": { - "idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "non_idempotent": [], + "retry_policy_1_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], + "no_retry_2_codes": [], + "no_retry_codes": [], + "retry_policy_2_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], + "no_retry_1_codes": [], }, "retry_params": { - "default": { + "retry_policy_1_params": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 60000, + }, + "retry_policy_2_params": { "initial_retry_delay_millis": 100, "retry_delay_multiplier": 1.3, "max_retry_delay_millis": 60000, "initial_rpc_timeout_millis": 480000, "rpc_timeout_multiplier": 1.0, "max_rpc_timeout_millis": 480000, - "total_timeout_millis": 600000, - } - }, - "methods": { - "GetIamPolicy": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "total_timeout_millis": 480000, }, - "GroupAssets": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", - }, - "GroupFindings": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "no_retry_params": { + "initial_retry_delay_millis": 0, + "retry_delay_multiplier": 0.0, + "max_retry_delay_millis": 0, + "initial_rpc_timeout_millis": 0, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 0, + "total_timeout_millis": 0, + }, + "no_retry_1_params": { + "initial_retry_delay_millis": 0, + "retry_delay_multiplier": 0.0, + "max_retry_delay_millis": 0, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 60000, }, - "TestIamPermissions": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "no_retry_2_params": { + "initial_retry_delay_millis": 0, + "retry_delay_multiplier": 0.0, + "max_retry_delay_millis": 0, + "initial_rpc_timeout_millis": 480000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 480000, + "total_timeout_millis": 480000, }, + }, + "methods": { "CreateSource": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "CreateFinding": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "CreateNotificationConfig": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "DeleteNotificationConfig": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", + }, + "GetIamPolicy": { + "timeout_millis": 60000, + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "GetNotificationConfig": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "GetOrganizationSettings": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "GetSource": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", + }, + "GroupAssets": { + "timeout_millis": 480000, + "retry_codes_name": "retry_policy_2_codes", + "retry_params_name": "retry_policy_2_params", + }, + "GroupFindings": { + "timeout_millis": 480000, + "retry_codes_name": "retry_policy_2_codes", + "retry_params_name": "retry_policy_2_params", }, "ListAssets": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "timeout_millis": 480000, + "retry_codes_name": "retry_policy_2_codes", + "retry_params_name": "retry_policy_2_params", }, "ListFindings": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "timeout_millis": 480000, + "retry_codes_name": "retry_policy_2_codes", + "retry_params_name": "retry_policy_2_params", }, "ListNotificationConfigs": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "ListSources": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "RunAssetDiscovery": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "SetFindingState": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "SetIamPolicy": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", + }, + "TestIamPermissions": { + "timeout_millis": 60000, + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "UpdateFinding": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "UpdateNotificationConfig": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "UpdateOrganizationSettings": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "UpdateSource": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "UpdateSecurityMarks": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "timeout_millis": 480000, + "retry_codes_name": "no_retry_2_codes", + "retry_params_name": "no_retry_2_params", }, }, } diff --git a/google/cloud/securitycenter_v1/gapic/transports/security_center_grpc_transport.py b/google/cloud/securitycenter_v1/gapic/transports/security_center_grpc_transport.py index 1d16b3f2..58249a17 100644 --- a/google/cloud/securitycenter_v1/gapic/transports/security_center_grpc_transport.py +++ b/google/cloud/securitycenter_v1/gapic/transports/security_center_grpc_transport.py @@ -120,63 +120,6 @@ def channel(self): """ return self._channel - @property - def get_iam_policy(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.get_iam_policy`. - - Gets the access control policy on the specified Source. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].GetIamPolicy - - @property - def group_assets(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.group_assets`. - - Filters an organization's assets and groups them by their specified - properties. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].GroupAssets - - @property - def group_findings(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.group_findings`. - - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. Example: - /v1/organizations/{organization_id}/sources/-/findings - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].GroupFindings - - @property - def test_iam_permissions(self): - """Return the gRPC stub for :meth:`SecurityCenterClient.test_iam_permissions`. - - Returns the permissions that a caller has on the specified source. - - Returns: - Callable: A callable which accepts the appropriate - deserialized request object and returns a - deserialized response object. - """ - return self._stubs["security_center_stub"].TestIamPermissions - @property def create_source(self): """Return the gRPC stub for :meth:`SecurityCenterClient.create_source`. @@ -230,6 +173,19 @@ def delete_notification_config(self): """ return self._stubs["security_center_stub"].DeleteNotificationConfig + @property + def get_iam_policy(self): + """Return the gRPC stub for :meth:`SecurityCenterClient.get_iam_policy`. + + Gets the access control policy on the specified Source. + + Returns: + Callable: A callable which accepts the appropriate + deserialized request object and returns a + deserialized response object. + """ + return self._stubs["security_center_stub"].GetIamPolicy + @property def get_notification_config(self): """Return the gRPC stub for :meth:`SecurityCenterClient.get_notification_config`. @@ -269,6 +225,37 @@ def get_source(self): """ return self._stubs["security_center_stub"].GetSource + @property + def group_assets(self): + """Return the gRPC stub for :meth:`SecurityCenterClient.group_assets`. + + Filters an organization's assets and groups them by their specified + properties. + + Returns: + Callable: A callable which accepts the appropriate + deserialized request object and returns a + deserialized response object. + """ + return self._stubs["security_center_stub"].GroupAssets + + @property + def group_findings(self): + """Return the gRPC stub for :meth:`SecurityCenterClient.group_findings`. + + Filters an organization or source's findings and groups them by + their specified properties. + + To group across all sources provide a ``-`` as the source id. Example: + /v1/organizations/{organization_id}/sources/-/findings + + Returns: + Callable: A callable which accepts the appropriate + deserialized request object and returns a + deserialized response object. + """ + return self._stubs["security_center_stub"].GroupFindings + @property def list_assets(self): """Return the gRPC stub for :meth:`SecurityCenterClient.list_assets`. @@ -368,6 +355,19 @@ def set_iam_policy(self): """ return self._stubs["security_center_stub"].SetIamPolicy + @property + def test_iam_permissions(self): + """Return the gRPC stub for :meth:`SecurityCenterClient.test_iam_permissions`. + + Returns the permissions that a caller has on the specified source. + + Returns: + Callable: A callable which accepts the appropriate + deserialized request object and returns a + deserialized response object. + """ + return self._stubs["security_center_stub"].TestIamPermissions + @property def update_finding(self): """Return the gRPC stub for :meth:`SecurityCenterClient.update_finding`. diff --git a/google/cloud/securitycenter_v1/proto/asset_pb2.py b/google/cloud/securitycenter_v1/proto/asset_pb2.py index 9f5e82a0..834f4147 100644 --- a/google/cloud/securitycenter_v1/proto/asset_pb2.py +++ b/google/cloud/securitycenter_v1/proto/asset_pb2.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/securitycenter_v1/proto/asset.proto - +"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection diff --git a/google/cloud/securitycenter_v1/proto/finding.proto b/google/cloud/securitycenter_v1/proto/finding.proto index 4ccdc495..cf0873cf 100644 --- a/google/cloud/securitycenter_v1/proto/finding.proto +++ b/google/cloud/securitycenter_v1/proto/finding.proto @@ -101,9 +101,11 @@ message Finding { // to the finding. SecurityMarks security_marks = 8 [(google.api.field_behavior) = OUTPUT_ONLY]; - // The time at which the event took place. For example, if the finding - // represents an open firewall it would capture the time the detector believes - // the firewall became open. The accuracy is determined by the detector. + // The time at which the event took place, or when an update to the finding + // occurred. For example, if the finding represents an open firewall it would + // capture the time the detector believes the firewall became open. The + // accuracy is determined by the detector. If the finding were to be resolved + // afterward, this time would reflect when the finding was resolved. google.protobuf.Timestamp event_time = 9; // The time at which the finding was created in Security Command Center. diff --git a/google/cloud/securitycenter_v1/proto/finding_pb2.py b/google/cloud/securitycenter_v1/proto/finding_pb2.py index c88d7a09..1730357e 100644 --- a/google/cloud/securitycenter_v1/proto/finding_pb2.py +++ b/google/cloud/securitycenter_v1/proto/finding_pb2.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/securitycenter_v1/proto/finding.proto - +"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection @@ -435,10 +435,12 @@ entirely managed by the user and come from the SecurityMarks resource that belongs to the finding. event_time: - The time at which the event took place. For example, if the - finding represents an open firewall it would capture the time - the detector believes the firewall became open. The accuracy - is determined by the detector. + The time at which the event took place, or when an update to + the finding occurred. For example, if the finding represents + an open firewall it would capture the time the detector + believes the firewall became open. The accuracy is determined + by the detector. If the finding were to be resolved afterward, + this time would reflect when the finding was resolved. create_time: The time at which the finding was created in Security Command Center. diff --git a/google/cloud/securitycenter_v1/proto/notification_config_pb2.py b/google/cloud/securitycenter_v1/proto/notification_config_pb2.py index bbd41547..5a318bba 100644 --- a/google/cloud/securitycenter_v1/proto/notification_config_pb2.py +++ b/google/cloud/securitycenter_v1/proto/notification_config_pb2.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/securitycenter_v1/proto/notification_config.proto - +"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection diff --git a/google/cloud/securitycenter_v1/proto/notification_message_pb2.py b/google/cloud/securitycenter_v1/proto/notification_message_pb2.py index eeb4372c..a7bd5d51 100644 --- a/google/cloud/securitycenter_v1/proto/notification_message_pb2.py +++ b/google/cloud/securitycenter_v1/proto/notification_message_pb2.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/securitycenter_v1/proto/notification_message.proto - +"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection diff --git a/google/cloud/securitycenter_v1/proto/organization_settings_pb2.py b/google/cloud/securitycenter_v1/proto/organization_settings_pb2.py index c8f94ad6..bd872c24 100644 --- a/google/cloud/securitycenter_v1/proto/organization_settings_pb2.py +++ b/google/cloud/securitycenter_v1/proto/organization_settings_pb2.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/securitycenter_v1/proto/organization_settings.proto - +"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection diff --git a/google/cloud/securitycenter_v1/proto/resource_pb2.py b/google/cloud/securitycenter_v1/proto/resource_pb2.py index 87bfb51c..c9c16fef 100644 --- a/google/cloud/securitycenter_v1/proto/resource_pb2.py +++ b/google/cloud/securitycenter_v1/proto/resource_pb2.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/securitycenter_v1/proto/resource.proto - +"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection diff --git a/google/cloud/securitycenter_v1/proto/run_asset_discovery_response_pb2.py b/google/cloud/securitycenter_v1/proto/run_asset_discovery_response_pb2.py index defd52f7..c4e2b2bd 100644 --- a/google/cloud/securitycenter_v1/proto/run_asset_discovery_response_pb2.py +++ b/google/cloud/securitycenter_v1/proto/run_asset_discovery_response_pb2.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/securitycenter_v1/proto/run_asset_discovery_response.proto - +"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection diff --git a/google/cloud/securitycenter_v1/proto/security_marks_pb2.py b/google/cloud/securitycenter_v1/proto/security_marks_pb2.py index f455b093..c110683b 100644 --- a/google/cloud/securitycenter_v1/proto/security_marks_pb2.py +++ b/google/cloud/securitycenter_v1/proto/security_marks_pb2.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/securitycenter_v1/proto/security_marks.proto - +"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection diff --git a/google/cloud/securitycenter_v1/proto/securitycenter_service_pb2.py b/google/cloud/securitycenter_v1/proto/securitycenter_service_pb2.py index 9cb7a6b1..4bb4b007 100644 --- a/google/cloud/securitycenter_v1/proto/securitycenter_service_pb2.py +++ b/google/cloud/securitycenter_v1/proto/securitycenter_service_pb2.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/securitycenter_v1/proto/securitycenter_service.proto - +"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection diff --git a/google/cloud/securitycenter_v1/proto/source_pb2.py b/google/cloud/securitycenter_v1/proto/source_pb2.py index 8e44d1d7..4d5792d1 100644 --- a/google/cloud/securitycenter_v1/proto/source_pb2.py +++ b/google/cloud/securitycenter_v1/proto/source_pb2.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/securitycenter_v1/proto/source.proto - +"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection diff --git a/google/cloud/securitycenter_v1beta1/__init__.py b/google/cloud/securitycenter_v1beta1/__init__.py index 55c3ce49..6944ab92 100644 --- a/google/cloud/securitycenter_v1beta1/__init__.py +++ b/google/cloud/securitycenter_v1beta1/__init__.py @@ -1,77 +1,45 @@ # -*- coding: utf-8 -*- - +# # Copyright 2020 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 +# 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. -# -from .services.security_center import SecurityCenterClient -from .types.asset import Asset -from .types.finding import Finding -from .types.organization_settings import OrganizationSettings -from .types.run_asset_discovery_response import RunAssetDiscoveryResponse -from .types.security_marks import SecurityMarks -from .types.securitycenter_service import CreateFindingRequest -from .types.securitycenter_service import CreateSourceRequest -from .types.securitycenter_service import GetOrganizationSettingsRequest -from .types.securitycenter_service import GetSourceRequest -from .types.securitycenter_service import GroupAssetsRequest -from .types.securitycenter_service import GroupAssetsResponse -from .types.securitycenter_service import GroupFindingsRequest -from .types.securitycenter_service import GroupFindingsResponse -from .types.securitycenter_service import GroupResult -from .types.securitycenter_service import ListAssetsRequest -from .types.securitycenter_service import ListAssetsResponse -from .types.securitycenter_service import ListFindingsRequest -from .types.securitycenter_service import ListFindingsResponse -from .types.securitycenter_service import ListSourcesRequest -from .types.securitycenter_service import ListSourcesResponse -from .types.securitycenter_service import RunAssetDiscoveryRequest -from .types.securitycenter_service import SetFindingStateRequest -from .types.securitycenter_service import UpdateFindingRequest -from .types.securitycenter_service import UpdateOrganizationSettingsRequest -from .types.securitycenter_service import UpdateSecurityMarksRequest -from .types.securitycenter_service import UpdateSourceRequest -from .types.source import Source + +from __future__ import absolute_import +import sys +import warnings + +from google.cloud.securitycenter_v1beta1 import types +from google.cloud.securitycenter_v1beta1.gapic import enums +from google.cloud.securitycenter_v1beta1.gapic import security_center_client + + +if sys.version_info[:2] == (2, 7): + message = ( + "A future version of this library will drop support for Python 2.7. " + "More details about Python 2 support for Google Cloud Client Libraries " + "can be found at https://cloud.google.com/python/docs/python2-sunset/" + ) + warnings.warn(message, DeprecationWarning) + + +class SecurityCenterClient(security_center_client.SecurityCenterClient): + __doc__ = security_center_client.SecurityCenterClient.__doc__ + enums = enums __all__ = ( - "Asset", - "CreateFindingRequest", - "CreateSourceRequest", - "Finding", - "GetOrganizationSettingsRequest", - "GetSourceRequest", - "GroupAssetsRequest", - "GroupAssetsResponse", - "GroupFindingsRequest", - "GroupFindingsResponse", - "GroupResult", - "ListAssetsRequest", - "ListAssetsResponse", - "ListFindingsRequest", - "ListFindingsResponse", - "ListSourcesRequest", - "ListSourcesResponse", - "OrganizationSettings", - "RunAssetDiscoveryRequest", - "RunAssetDiscoveryResponse", - "SecurityMarks", - "SetFindingStateRequest", - "Source", - "UpdateFindingRequest", - "UpdateOrganizationSettingsRequest", - "UpdateSecurityMarksRequest", - "UpdateSourceRequest", + "enums", + "types", "SecurityCenterClient", ) diff --git a/google/cloud/securitycenter_v1beta1/gapic/security_center_client.py b/google/cloud/securitycenter_v1beta1/gapic/security_center_client.py index 72660006..bc638425 100644 --- a/google/cloud/securitycenter_v1beta1/gapic/security_center_client.py +++ b/google/cloud/securitycenter_v1beta1/gapic/security_center_client.py @@ -89,15 +89,6 @@ def from_service_account_file(cls, filename, *args, **kwargs): from_service_account_json = from_service_account_file - @classmethod - def asset_security_marks_path(cls, organization, asset): - """Return a fully-qualified asset_security_marks string.""" - return google.api_core.path_template.expand( - "organizations/{organization}/assets/{asset}/securityMarks", - organization=organization, - asset=asset, - ) - @classmethod def finding_path(cls, organization, source, finding): """Return a fully-qualified finding string.""" @@ -108,16 +99,6 @@ def finding_path(cls, organization, source, finding): finding=finding, ) - @classmethod - def finding_security_marks_path(cls, organization, source, finding): - """Return a fully-qualified finding_security_marks string.""" - return google.api_core.path_template.expand( - "organizations/{organization}/sources/{source}/findings/{finding}/securityMarks", - organization=organization, - source=source, - finding=finding, - ) - @classmethod def organization_path(cls, organization): """Return a fully-qualified organization string.""" @@ -133,6 +114,15 @@ def organization_settings_path(cls, organization): organization=organization, ) + @classmethod + def security_marks_path(cls, organization, asset): + """Return a fully-qualified security_marks string.""" + return google.api_core.path_template.expand( + "organizations/{organization}/assets/{asset}/securityMarks", + organization=organization, + asset=asset, + ) + @classmethod def source_path(cls, organization, source): """Return a fully-qualified source string.""" @@ -441,7 +431,8 @@ def get_iam_policy( >>> >>> client = securitycenter_v1beta1.SecurityCenterClient() >>> - >>> resource = client.source_path('[ORGANIZATION]', '[SOURCE]') + >>> # TODO: Initialize `resource`: + >>> resource = '' >>> >>> response = client.get_iam_policy(resource) @@ -1647,7 +1638,8 @@ def set_iam_policy( >>> >>> client = securitycenter_v1beta1.SecurityCenterClient() >>> - >>> resource = client.source_path('[ORGANIZATION]', '[SOURCE]') + >>> # TODO: Initialize `resource`: + >>> resource = '' >>> >>> # TODO: Initialize `policy`: >>> policy = {} @@ -1728,7 +1720,8 @@ def test_iam_permissions( >>> >>> client = securitycenter_v1beta1.SecurityCenterClient() >>> - >>> resource = client.source_path('[ORGANIZATION]', '[SOURCE]') + >>> # TODO: Initialize `resource`: + >>> resource = '' >>> >>> # TODO: Initialize `permissions`: >>> permissions = [] diff --git a/google/cloud/securitycenter_v1beta1/gapic/security_center_client_config.py b/google/cloud/securitycenter_v1beta1/gapic/security_center_client_config.py index 9b5c01a9..6d6b421b 100644 --- a/google/cloud/securitycenter_v1beta1/gapic/security_center_client_config.py +++ b/google/cloud/securitycenter_v1beta1/gapic/security_center_client_config.py @@ -2,110 +2,149 @@ "interfaces": { "google.cloud.securitycenter.v1beta1.SecurityCenter": { "retry_codes": { - "idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "non_idempotent": [], + "retry_policy_1_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], + "no_retry_2_codes": [], + "no_retry_codes": [], + "retry_policy_2_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], + "no_retry_1_codes": [], }, "retry_params": { - "default": { + "retry_policy_1_params": { "initial_retry_delay_millis": 100, "retry_delay_multiplier": 1.3, "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 20000, + "initial_rpc_timeout_millis": 60000, "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 20000, - "total_timeout_millis": 600000, - } + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 60000, + }, + "retry_policy_2_params": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 480000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 480000, + "total_timeout_millis": 480000, + }, + "no_retry_params": { + "initial_retry_delay_millis": 0, + "retry_delay_multiplier": 0.0, + "max_retry_delay_millis": 0, + "initial_rpc_timeout_millis": 0, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 0, + "total_timeout_millis": 0, + }, + "no_retry_1_params": { + "initial_retry_delay_millis": 0, + "retry_delay_multiplier": 0.0, + "max_retry_delay_millis": 0, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 60000, + }, + "no_retry_2_params": { + "initial_retry_delay_millis": 0, + "retry_delay_multiplier": 0.0, + "max_retry_delay_millis": 0, + "initial_rpc_timeout_millis": 480000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 480000, + "total_timeout_millis": 480000, + }, }, "methods": { "CreateSource": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "CreateFinding": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "GetIamPolicy": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "GetOrganizationSettings": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "GetSource": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "GroupAssets": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "timeout_millis": 480000, + "retry_codes_name": "retry_policy_2_codes", + "retry_params_name": "retry_policy_2_params", }, "GroupFindings": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "timeout_millis": 480000, + "retry_codes_name": "retry_policy_2_codes", + "retry_params_name": "retry_policy_2_params", }, "ListAssets": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "timeout_millis": 480000, + "retry_codes_name": "retry_policy_2_codes", + "retry_params_name": "retry_policy_2_params", }, "ListFindings": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "timeout_millis": 480000, + "retry_codes_name": "retry_policy_2_codes", + "retry_params_name": "retry_policy_2_params", }, "ListSources": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "RunAssetDiscovery": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "SetFindingState": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "SetIamPolicy": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "TestIamPermissions": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "UpdateFinding": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "UpdateOrganizationSettings": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "UpdateSource": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "UpdateSecurityMarks": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "timeout_millis": 480000, + "retry_codes_name": "no_retry_2_codes", + "retry_params_name": "no_retry_2_params", }, }, } diff --git a/google/cloud/securitycenter_v1beta1/proto/asset_pb2.py b/google/cloud/securitycenter_v1beta1/proto/asset_pb2.py index e1e488ee..ecef17ea 100644 --- a/google/cloud/securitycenter_v1beta1/proto/asset_pb2.py +++ b/google/cloud/securitycenter_v1beta1/proto/asset_pb2.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/securitycenter_v1beta1/proto/asset.proto - +"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection @@ -13,6 +13,7 @@ from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 +from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 from google.cloud.securitycenter_v1beta1.proto import ( security_marks_pb2 as google_dot_cloud_dot_securitycenter__v1beta1_dot_proto_dot_security__marks__pb2, ) @@ -27,9 +28,10 @@ syntax="proto3", serialized_options=b"\n'com.google.cloud.securitycenter.v1beta1P\001ZQgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1;securitycenter", create_key=_descriptor._internal_create_key, - serialized_pb=b"\n5google/cloud/securitycenter_v1beta1/proto/asset.proto\x12#google.cloud.securitycenter.v1beta1\x1a\x1fgoogle/api/field_behavior.proto\x1a>google/cloud/securitycenter_v1beta1/proto/security_marks.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1cgoogle/api/annotations.proto\"\xfc\x04\n\x05\x41sset\x12\x0c\n\x04name\x18\x01 \x01(\t\x12g\n\x1asecurity_center_properties\x18\x02 \x01(\x0b\x32\x43.google.cloud.securitycenter.v1beta1.Asset.SecurityCenterProperties\x12_\n\x13resource_properties\x18\x07 \x03(\x0b\x32\x42.google.cloud.securitycenter.v1beta1.Asset.ResourcePropertiesEntry\x12J\n\x0esecurity_marks\x18\x08 \x01(\x0b\x32\x32.google.cloud.securitycenter.v1beta1.SecurityMarks\x12/\n\x0b\x63reate_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0bupdate_time\x18\n \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x1a\x99\x01\n\x18SecurityCenterProperties\x12\x1a\n\rresource_name\x18\x01 \x01(\tB\x03\xe0\x41\x05\x12\x15\n\rresource_type\x18\x02 \x01(\t\x12\x17\n\x0fresource_parent\x18\x03 \x01(\t\x12\x18\n\x10resource_project\x18\x04 \x01(\t\x12\x17\n\x0fresource_owners\x18\x05 \x03(\t\x1aQ\n\x17ResourcePropertiesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12%\n\x05value\x18\x02 \x01(\x0b\x32\x16.google.protobuf.Value:\x02\x38\x01\x42~\n'com.google.cloud.securitycenter.v1beta1P\x01ZQgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1;securitycenterb\x06proto3", + serialized_pb=b"\n5google/cloud/securitycenter_v1beta1/proto/asset.proto\x12#google.cloud.securitycenter.v1beta1\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a>google/cloud/securitycenter_v1beta1/proto/security_marks.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1cgoogle/api/annotations.proto\"\xd3\x05\n\x05\x41sset\x12\x0c\n\x04name\x18\x01 \x01(\t\x12g\n\x1asecurity_center_properties\x18\x02 \x01(\x0b\x32\x43.google.cloud.securitycenter.v1beta1.Asset.SecurityCenterProperties\x12_\n\x13resource_properties\x18\x07 \x03(\x0b\x32\x42.google.cloud.securitycenter.v1beta1.Asset.ResourcePropertiesEntry\x12J\n\x0esecurity_marks\x18\x08 \x01(\x0b\x32\x32.google.cloud.securitycenter.v1beta1.SecurityMarks\x12/\n\x0b\x63reate_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0bupdate_time\x18\n \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x1a\x99\x01\n\x18SecurityCenterProperties\x12\x1a\n\rresource_name\x18\x01 \x01(\tB\x03\xe0\x41\x05\x12\x15\n\rresource_type\x18\x02 \x01(\t\x12\x17\n\x0fresource_parent\x18\x03 \x01(\t\x12\x18\n\x10resource_project\x18\x04 \x01(\t\x12\x17\n\x0fresource_owners\x18\x05 \x03(\t\x1aQ\n\x17ResourcePropertiesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12%\n\x05value\x18\x02 \x01(\x0b\x32\x16.google.protobuf.Value:\x02\x38\x01:U\xea\x41R\n#securitycenter.googleapis.com/Asset\x12+organizations/{organization}/assets/{asset}B~\n'com.google.cloud.securitycenter.v1beta1P\x01ZQgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1;securitycenterb\x06proto3", dependencies=[ google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, + google_dot_api_dot_resource__pb2.DESCRIPTOR, google_dot_cloud_dot_securitycenter__v1beta1_dot_proto_dot_security__marks__pb2.DESCRIPTOR, google_dot_protobuf_dot_struct__pb2.DESCRIPTOR, google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, @@ -150,8 +152,8 @@ syntax="proto3", extension_ranges=[], oneofs=[], - serialized_start=685, - serialized_end=838, + serialized_start=712, + serialized_end=865, ) _ASSET_RESOURCEPROPERTIESENTRY = _descriptor.Descriptor( @@ -209,8 +211,8 @@ syntax="proto3", extension_ranges=[], oneofs=[], - serialized_start=840, - serialized_end=921, + serialized_start=867, + serialized_end=948, ) _ASSET = _descriptor.Descriptor( @@ -339,13 +341,13 @@ extensions=[], nested_types=[_ASSET_SECURITYCENTERPROPERTIES, _ASSET_RESOURCEPROPERTIESENTRY,], enum_types=[], - serialized_options=None, + serialized_options=b"\352AR\n#securitycenter.googleapis.com/Asset\022+organizations/{organization}/assets/{asset}", is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], - serialized_start=285, - serialized_end=921, + serialized_start=312, + serialized_end=1035, ) _ASSET_SECURITYCENTERPROPERTIES.containing_type = _ASSET @@ -383,20 +385,21 @@ { "DESCRIPTOR": _ASSET_SECURITYCENTERPROPERTIES, "__module__": "google.cloud.securitycenter_v1beta1.proto.asset_pb2", - "__doc__": """Cloud SCC managed properties. These properties are managed by Cloud - SCC and cannot be modified by the user. + "__doc__": """Security Command Center managed properties. These properties are + managed by Security Command Center and cannot be modified by the user. Attributes: resource_name: - Immutable. The full resource name of the GCP resource this - asset represents. This field is immutable after create time. - See: https://cloud.google.com/apis/design/resource_names#full_ - resource_name + Immutable. The full resource name of the Google Cloud resource + this asset represents. This field is immutable after create + time. See: https://cloud.google.com/apis/design/resource_names + #full_resource_name resource_type: - The type of the GCP resource. Examples include: APPLICATION, - PROJECT, and ORGANIZATION. This is a case insensitive field - defined by Cloud SCC and/or the producer of the resource and - is immutable after create time. + The type of the Google Cloud resource. Examples include: + APPLICATION, PROJECT, and ORGANIZATION. This is a case + insensitive field defined by Security Command Center and/or + the producer of the resource and is immutable after create + time. resource_parent: The full resource name of the immediate parent of the resource. See: https://cloud.google.com/apis/design/resource_n @@ -422,11 +425,11 @@ ), "DESCRIPTOR": _ASSET, "__module__": "google.cloud.securitycenter_v1beta1.proto.asset_pb2", - "__doc__": """Cloud Security Command Center’s (Cloud SCC) representation of a Google - Cloud Platform (GCP) resource. The Asset is a Cloud SCC resource that - captures information about a single GCP resource. All modifications to - an Asset are only within the context of Cloud SCC and don’t affect the - referenced GCP resource. + "__doc__": """Security Command Center representation of a Google Cloud resource. + The Asset is a Security Command Center resource that captures + information about a single Google Cloud resource. All modifications to + an Asset are only within the context of Security Command Center and + don’t affect the referenced Google Cloud resource. Attributes: name: @@ -434,21 +437,23 @@ oogle.com/apis/design/resource_names#relative_resource_name Example: “organizations/{organization_id}/assets/{asset_id}”. security_center_properties: - Cloud SCC managed properties. These properties are managed by - Cloud SCC and cannot be modified by the user. + Security Command Center managed properties. These properties + are managed by Security Command Center and cannot be modified + by the user. resource_properties: Resource managed properties. These properties are managed and - defined by the GCP resource and cannot be modified by the - user. + defined by the Google Cloud resource and cannot be modified by + the user. security_marks: User specified security marks. These marks are entirely managed by the user and come from the SecurityMarks resource that belongs to the asset. create_time: - The time at which the asset was created in Cloud SCC. + The time at which the asset was created in Security Command + Center. update_time: The time at which the asset was last updated, added, or - deleted in Cloud SCC. + deleted in Security Command Center. """, # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.Asset) }, @@ -461,4 +466,5 @@ DESCRIPTOR._options = None _ASSET_SECURITYCENTERPROPERTIES.fields_by_name["resource_name"]._options = None _ASSET_RESOURCEPROPERTIESENTRY._options = None +_ASSET._options = None # @@protoc_insertion_point(module_scope) diff --git a/google/cloud/securitycenter_v1beta1/proto/finding.proto b/google/cloud/securitycenter_v1beta1/proto/finding.proto index d78a522b..647b3b43 100644 --- a/google/cloud/securitycenter_v1beta1/proto/finding.proto +++ b/google/cloud/securitycenter_v1beta1/proto/finding.proto @@ -16,12 +16,12 @@ syntax = "proto3"; package google.cloud.securitycenter.v1beta1; +import "google/api/annotations.proto"; import "google/api/field_behavior.proto"; import "google/api/resource.proto"; import "google/cloud/securitycenter/v1beta1/security_marks.proto"; import "google/protobuf/struct.proto"; import "google/protobuf/timestamp.proto"; -import "google/api/annotations.proto"; option go_package = "google.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1;securitycenter"; option java_multiple_files = true; @@ -58,7 +58,8 @@ message Finding { // "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}" string name = 1; - // Immutable. The relative resource name of the source the finding belongs to. See: + // Immutable. The relative resource name of the source the finding belongs to. + // See: // https://cloud.google.com/apis/design/resource_names#relative_resource_name // This field is immutable after creation time. // For example: @@ -97,9 +98,11 @@ message Finding { // to the finding. SecurityMarks security_marks = 8 [(google.api.field_behavior) = OUTPUT_ONLY]; - // The time at which the event took place. For example, if the finding - // represents an open firewall it would capture the time the detector believes - // the firewall became open. The accuracy is determined by the detector. + // The time at which the event took place, or when an update to the finding + // occurred. For example, if the finding represents an open firewall it would + // capture the time the detector believes the firewall became open. The + // accuracy is determined by the detector. If the finding were to be resolved + // afterward, this time would reflect when the finding was resolved. google.protobuf.Timestamp event_time = 9; // The time at which the finding was created in Security Command Center. diff --git a/google/cloud/securitycenter_v1beta1/proto/finding_pb2.py b/google/cloud/securitycenter_v1beta1/proto/finding_pb2.py index 0c7b8e81..b62cd8a8 100644 --- a/google/cloud/securitycenter_v1beta1/proto/finding_pb2.py +++ b/google/cloud/securitycenter_v1beta1/proto/finding_pb2.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/securitycenter_v1beta1/proto/finding.proto - +"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection @@ -12,6 +12,7 @@ _sym_db = _symbol_database.Default() +from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 from google.api import field_behavior_pb2 as google_dot_api_dot_field__behavior__pb2 from google.api import resource_pb2 as google_dot_api_dot_resource__pb2 from google.cloud.securitycenter_v1beta1.proto import ( @@ -19,7 +20,6 @@ ) from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 -from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 DESCRIPTOR = _descriptor.FileDescriptor( @@ -28,14 +28,14 @@ syntax="proto3", serialized_options=b"\n'com.google.cloud.securitycenter.v1beta1P\001ZQgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1;securitycenter", create_key=_descriptor._internal_create_key, - serialized_pb=b'\n7google/cloud/securitycenter_v1beta1/proto/finding.proto\x12#google.cloud.securitycenter.v1beta1\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a>google/cloud/securitycenter_v1beta1/proto/security_marks.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a\x1cgoogle/api/annotations.proto"\xb8\x05\n\x07\x46inding\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x13\n\x06parent\x18\x02 \x01(\tB\x03\xe0\x41\x05\x12\x15\n\rresource_name\x18\x03 \x01(\t\x12\x41\n\x05state\x18\x04 \x01(\x0e\x32\x32.google.cloud.securitycenter.v1beta1.Finding.State\x12\x10\n\x08\x63\x61tegory\x18\x05 \x01(\t\x12\x14\n\x0c\x65xternal_uri\x18\x06 \x01(\t\x12]\n\x11source_properties\x18\x07 \x03(\x0b\x32\x42.google.cloud.securitycenter.v1beta1.Finding.SourcePropertiesEntry\x12O\n\x0esecurity_marks\x18\x08 \x01(\x0b\x32\x32.google.cloud.securitycenter.v1beta1.SecurityMarksB\x03\xe0\x41\x03\x12.\n\nevent_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0b\x63reate_time\x18\n \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x1aO\n\x15SourcePropertiesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12%\n\x05value\x18\x02 \x01(\x0b\x32\x16.google.protobuf.Value:\x02\x38\x01"8\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\n\n\x06\x41\x43TIVE\x10\x01\x12\x0c\n\x08INACTIVE\x10\x02:l\xea\x41i\n%securitycenter.googleapis.com/Finding\x12@organizations/{organization}/sources/{source}/findings/{finding}B~\n\'com.google.cloud.securitycenter.v1beta1P\x01ZQgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1;securitycenterb\x06proto3', + serialized_pb=b'\n7google/cloud/securitycenter_v1beta1/proto/finding.proto\x12#google.cloud.securitycenter.v1beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a>google/cloud/securitycenter_v1beta1/proto/security_marks.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\xb8\x05\n\x07\x46inding\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x13\n\x06parent\x18\x02 \x01(\tB\x03\xe0\x41\x05\x12\x15\n\rresource_name\x18\x03 \x01(\t\x12\x41\n\x05state\x18\x04 \x01(\x0e\x32\x32.google.cloud.securitycenter.v1beta1.Finding.State\x12\x10\n\x08\x63\x61tegory\x18\x05 \x01(\t\x12\x14\n\x0c\x65xternal_uri\x18\x06 \x01(\t\x12]\n\x11source_properties\x18\x07 \x03(\x0b\x32\x42.google.cloud.securitycenter.v1beta1.Finding.SourcePropertiesEntry\x12O\n\x0esecurity_marks\x18\x08 \x01(\x0b\x32\x32.google.cloud.securitycenter.v1beta1.SecurityMarksB\x03\xe0\x41\x03\x12.\n\nevent_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0b\x63reate_time\x18\n \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x1aO\n\x15SourcePropertiesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12%\n\x05value\x18\x02 \x01(\x0b\x32\x16.google.protobuf.Value:\x02\x38\x01"8\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\n\n\x06\x41\x43TIVE\x10\x01\x12\x0c\n\x08INACTIVE\x10\x02:l\xea\x41i\n%securitycenter.googleapis.com/Finding\x12@organizations/{organization}/sources/{source}/findings/{finding}B~\n\'com.google.cloud.securitycenter.v1beta1P\x01ZQgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1beta1;securitycenterb\x06proto3', dependencies=[ + google_dot_api_dot_annotations__pb2.DESCRIPTOR, google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, google_dot_api_dot_resource__pb2.DESCRIPTOR, google_dot_cloud_dot_securitycenter__v1beta1_dot_proto_dot_security__marks__pb2.DESCRIPTOR, google_dot_protobuf_dot_struct__pb2.DESCRIPTOR, google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR, - google_dot_api_dot_annotations__pb2.DESCRIPTOR, ], ) @@ -388,9 +388,9 @@ ), "DESCRIPTOR": _FINDING, "__module__": "google.cloud.securitycenter_v1beta1.proto.finding_pb2", - "__doc__": """Cloud Security Command Center (Cloud SCC) finding. A finding is a - record of assessment data (security, risk, health or privacy) ingested - into Cloud SCC for presentation, notification, analysis, policy + "__doc__": """Security Command Center finding. A finding is a record of assessment + data (security, risk, health or privacy) ingested into Security + Command Center for presentation, notification, analysis, policy testing, and enforcement. For example, an XSS vulnerability in an App Engine application is a finding. @@ -407,10 +407,10 @@ after creation time. For example: “organizations/{organization_id}/sources/{source_id}” resource_name: - For findings on Google Cloud Platform (GCP) resources, the - full resource name of the GCP resource this finding is for. - See: https://cloud.google.com/apis/design/resource_names#full_ - resource_name When the finding is for a non-GCP resource, the + For findings on Google Cloud resources, the full resource name + of the Google Cloud resource this finding is for. See: https:/ + /cloud.google.com/apis/design/resource_names#full_resource_nam + e When the finding is for a non-Google Cloud resource, the resourceName can be a customer or partner defined string. This field is immutable after creation time. state: @@ -421,9 +421,9 @@ “XSS_FLASH_INJECTION” external_uri: The URI that, if available, points to a web page outside of - Cloud SCC where additional information about the finding can - be found. This field is guaranteed to be either empty or a - well formed URL. + Security Command Center where additional information about the + finding can be found. This field is guaranteed to be either + empty or a well formed URL. source_properties: Source specific properties. These properties are managed by the source that writes the finding. The key names in the @@ -435,12 +435,15 @@ entirely managed by the user and come from the SecurityMarks resource that belongs to the finding. event_time: - The time at which the event took place. For example, if the - finding represents an open firewall it would capture the time - the detector believes the firewall became open. The accuracy - is determined by the detector. + The time at which the event took place, or when an update to + the finding occurred. For example, if the finding represents + an open firewall it would capture the time the detector + believes the firewall became open. The accuracy is determined + by the detector. If the finding were to be resolved afterward, + this time would reflect when the finding was resolved. create_time: - The time at which the finding was created in Cloud SCC. + The time at which the finding was created in Security Command + Center. """, # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1beta1.Finding) }, diff --git a/google/cloud/securitycenter_v1beta1/proto/organization_settings_pb2.py b/google/cloud/securitycenter_v1beta1/proto/organization_settings_pb2.py index 779190be..0482472a 100644 --- a/google/cloud/securitycenter_v1beta1/proto/organization_settings_pb2.py +++ b/google/cloud/securitycenter_v1beta1/proto/organization_settings_pb2.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/securitycenter_v1beta1/proto/organization_settings.proto - +"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection @@ -243,8 +243,8 @@ ), "DESCRIPTOR": _ORGANIZATIONSETTINGS, "__module__": "google.cloud.securitycenter_v1beta1.proto.organization_settings_pb2", - "__doc__": """User specified settings that are attached to the Cloud Security - Command Center (Cloud SCC) organization. + "__doc__": """User specified settings that are attached to the Security Command + Center organization. Attributes: name: diff --git a/google/cloud/securitycenter_v1beta1/proto/run_asset_discovery_response_pb2.py b/google/cloud/securitycenter_v1beta1/proto/run_asset_discovery_response_pb2.py index dc17572d..6084afdf 100644 --- a/google/cloud/securitycenter_v1beta1/proto/run_asset_discovery_response_pb2.py +++ b/google/cloud/securitycenter_v1beta1/proto/run_asset_discovery_response_pb2.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/securitycenter_v1beta1/proto/run_asset_discovery_response.proto - +"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection diff --git a/google/cloud/securitycenter_v1beta1/proto/security_marks_pb2.py b/google/cloud/securitycenter_v1beta1/proto/security_marks_pb2.py index a9cae49e..144c51d3 100644 --- a/google/cloud/securitycenter_v1beta1/proto/security_marks_pb2.py +++ b/google/cloud/securitycenter_v1beta1/proto/security_marks_pb2.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/securitycenter_v1beta1/proto/security_marks.proto - +"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection @@ -168,10 +168,10 @@ ), "DESCRIPTOR": _SECURITYMARKS, "__module__": "google.cloud.securitycenter_v1beta1.proto.security_marks_pb2", - "__doc__": """User specified security marks that are attached to the parent Cloud - Security Command Center (Cloud SCC) resource. Security marks are - scoped within a Cloud SCC organization – they can be modified and - viewed by all users who have proper permissions on the organization. + "__doc__": """User specified security marks that are attached to the parent Security + Command Center resource. Security marks are scoped within a Security + Command Center organization – they can be modified and viewed by all + users who have proper permissions on the organization. Attributes: name: diff --git a/google/cloud/securitycenter_v1beta1/proto/securitycenter_service_pb2.py b/google/cloud/securitycenter_v1beta1/proto/securitycenter_service_pb2.py index 98f66db7..8616e6cb 100644 --- a/google/cloud/securitycenter_v1beta1/proto/securitycenter_service_pb2.py +++ b/google/cloud/securitycenter_v1beta1/proto/securitycenter_service_pb2.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/securitycenter_v1beta1/proto/securitycenter_service.proto - +"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection diff --git a/google/cloud/securitycenter_v1beta1/proto/source_pb2.py b/google/cloud/securitycenter_v1beta1/proto/source_pb2.py index 835fccd5..012d09ce 100644 --- a/google/cloud/securitycenter_v1beta1/proto/source_pb2.py +++ b/google/cloud/securitycenter_v1beta1/proto/source_pb2.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/securitycenter_v1beta1/proto/source.proto - +"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection @@ -117,10 +117,10 @@ { "DESCRIPTOR": _SOURCE, "__module__": "google.cloud.securitycenter_v1beta1.proto.source_pb2", - "__doc__": """Cloud Security Command Center’s (Cloud SCC) finding source. A finding - source is an entity or a mechanism that can produce a finding. A - source is like a container of findings that come from the same - scanner, logger, monitor, etc. + "__doc__": """Security Command Center finding source. A finding source is an entity + or a mechanism that can produce a finding. A source is like a + container of findings that come from the same scanner, logger, + monitor, etc. Attributes: name: @@ -135,7 +135,7 @@ (inclusive). description: The description of the source (max of 1024 characters). - Example: “Cloud Security Scanner is a web security scanner for + Example: “Web Security Scanner is a web security scanner for common vulnerabilities in App Engine applications. It can automatically scan and detect four common vulnerabilities, including cross-site-scripting (XSS), Flash injection, mixed diff --git a/google/cloud/securitycenter_v1p1beta1/__init__.py b/google/cloud/securitycenter_v1p1beta1/__init__.py index 27c3ed04..5e528124 100644 --- a/google/cloud/securitycenter_v1p1beta1/__init__.py +++ b/google/cloud/securitycenter_v1p1beta1/__init__.py @@ -1,95 +1,45 @@ # -*- coding: utf-8 -*- - +# # Copyright 2020 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 +# 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. -# -from .services.security_center import SecurityCenterClient -from .types.asset import Asset -from .types.finding import Finding -from .types.notification_config import NotificationConfig -from .types.notification_message import NotificationMessage -from .types.organization_settings import OrganizationSettings -from .types.resource import Resource -from .types.run_asset_discovery_response import RunAssetDiscoveryResponse -from .types.security_marks import SecurityMarks -from .types.securitycenter_service import CreateFindingRequest -from .types.securitycenter_service import CreateNotificationConfigRequest -from .types.securitycenter_service import CreateSourceRequest -from .types.securitycenter_service import DeleteNotificationConfigRequest -from .types.securitycenter_service import GetNotificationConfigRequest -from .types.securitycenter_service import GetOrganizationSettingsRequest -from .types.securitycenter_service import GetSourceRequest -from .types.securitycenter_service import GroupAssetsRequest -from .types.securitycenter_service import GroupAssetsResponse -from .types.securitycenter_service import GroupFindingsRequest -from .types.securitycenter_service import GroupFindingsResponse -from .types.securitycenter_service import GroupResult -from .types.securitycenter_service import ListAssetsRequest -from .types.securitycenter_service import ListAssetsResponse -from .types.securitycenter_service import ListFindingsRequest -from .types.securitycenter_service import ListFindingsResponse -from .types.securitycenter_service import ListNotificationConfigsRequest -from .types.securitycenter_service import ListNotificationConfigsResponse -from .types.securitycenter_service import ListSourcesRequest -from .types.securitycenter_service import ListSourcesResponse -from .types.securitycenter_service import RunAssetDiscoveryRequest -from .types.securitycenter_service import SetFindingStateRequest -from .types.securitycenter_service import UpdateFindingRequest -from .types.securitycenter_service import UpdateNotificationConfigRequest -from .types.securitycenter_service import UpdateOrganizationSettingsRequest -from .types.securitycenter_service import UpdateSecurityMarksRequest -from .types.securitycenter_service import UpdateSourceRequest -from .types.source import Source + +from __future__ import absolute_import +import sys +import warnings + +from google.cloud.securitycenter_v1p1beta1 import types +from google.cloud.securitycenter_v1p1beta1.gapic import enums +from google.cloud.securitycenter_v1p1beta1.gapic import security_center_client + + +if sys.version_info[:2] == (2, 7): + message = ( + "A future version of this library will drop support for Python 2.7. " + "More details about Python 2 support for Google Cloud Client Libraries " + "can be found at https://cloud.google.com/python/docs/python2-sunset/" + ) + warnings.warn(message, DeprecationWarning) + + +class SecurityCenterClient(security_center_client.SecurityCenterClient): + __doc__ = security_center_client.SecurityCenterClient.__doc__ + enums = enums __all__ = ( - "Asset", - "CreateFindingRequest", - "CreateNotificationConfigRequest", - "CreateSourceRequest", - "DeleteNotificationConfigRequest", - "Finding", - "GetNotificationConfigRequest", - "GetOrganizationSettingsRequest", - "GetSourceRequest", - "GroupAssetsRequest", - "GroupAssetsResponse", - "GroupFindingsRequest", - "GroupFindingsResponse", - "GroupResult", - "ListAssetsRequest", - "ListAssetsResponse", - "ListFindingsRequest", - "ListFindingsResponse", - "ListNotificationConfigsRequest", - "ListNotificationConfigsResponse", - "ListSourcesRequest", - "ListSourcesResponse", - "NotificationConfig", - "NotificationMessage", - "OrganizationSettings", - "Resource", - "RunAssetDiscoveryRequest", - "RunAssetDiscoveryResponse", - "SecurityMarks", - "SetFindingStateRequest", - "Source", - "UpdateFindingRequest", - "UpdateNotificationConfigRequest", - "UpdateOrganizationSettingsRequest", - "UpdateSecurityMarksRequest", - "UpdateSourceRequest", + "enums", + "types", "SecurityCenterClient", ) diff --git a/google/cloud/securitycenter_v1p1beta1/gapic/enums.py b/google/cloud/securitycenter_v1p1beta1/gapic/enums.py index 9dc872dd..9a308dd5 100644 --- a/google/cloud/securitycenter_v1p1beta1/gapic/enums.py +++ b/google/cloud/securitycenter_v1p1beta1/gapic/enums.py @@ -34,6 +34,24 @@ class NullValue(enum.IntEnum): class Finding(object): + class Severity(enum.IntEnum): + """ + The severity of the finding. + + Attributes: + SEVERITY_UNSPECIFIED (int): No severity specified. The default value. + CRITICAL (int): Critical severity. + HIGH (int): High severity. + MEDIUM (int): Medium severity. + LOW (int): Low severity. + """ + + SEVERITY_UNSPECIFIED = 0 + CRITICAL = 1 + HIGH = 2 + MEDIUM = 3 + LOW = 4 + class State(enum.IntEnum): """ The state of the finding. diff --git a/google/cloud/securitycenter_v1p1beta1/gapic/security_center_client.py b/google/cloud/securitycenter_v1p1beta1/gapic/security_center_client.py index 6e667b1c..b236e9f0 100644 --- a/google/cloud/securitycenter_v1p1beta1/gapic/security_center_client.py +++ b/google/cloud/securitycenter_v1p1beta1/gapic/security_center_client.py @@ -376,8 +376,6 @@ def create_finding( parent (str): Required. Resource name of the new finding's parent. Its format should be "organizations/[organization_id]/sources/[source_id]". finding_id (str): Required. Unique identifier provided by the client within the parent scope. - It must be alphanumeric and less than or equal to 32 characters and - greater than 0 characters in length. finding (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.Finding]): Required. The Finding being created. The name and security_marks will be ignored as they are both output only fields on this resource. @@ -467,9 +465,8 @@ def create_notification_config( Unique identifier provided by the client within the parent scope. It must be between 1 and 128 characters, and contains alphanumeric characters, underscores or hyphens only. - notification_config (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.NotificationConfig]): Required. The notification config being created. The name and the service - account will be ignored as they are both output only fields on this - resource. + notification_config (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.NotificationConfig]): Required. The notification config being created. The name and the service account + will be ignored as they are both output only fields on this resource. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.securitycenter_v1p1beta1.types.NotificationConfig` @@ -1526,8 +1523,7 @@ def list_assets( If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.securitycenter_v1p1beta1.types.Duration` - field_mask (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.FieldMask]): Optional. - A field mask to specify the ListAssetsResult fields to be listed in the + field_mask (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.FieldMask]): A field mask to specify the ListAssetsResult fields to be listed in the response. An empty field mask will list all fields. @@ -1748,8 +1744,7 @@ def list_findings( If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.securitycenter_v1p1beta1.types.Duration` - field_mask (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.FieldMask]): Optional. - A field mask to specify the Finding fields to be listed in the response. + field_mask (Union[dict, ~google.cloud.securitycenter_v1p1beta1.types.FieldMask]): A field mask to specify the Finding fields to be listed in the response. An empty field mask will list all fields. If a dict is provided, it must be of the same form as the protobuf diff --git a/google/cloud/securitycenter_v1p1beta1/gapic/security_center_client_config.py b/google/cloud/securitycenter_v1p1beta1/gapic/security_center_client_config.py index 975998d8..1f6297b6 100644 --- a/google/cloud/securitycenter_v1p1beta1/gapic/security_center_client_config.py +++ b/google/cloud/securitycenter_v1p1beta1/gapic/security_center_client_config.py @@ -2,135 +2,174 @@ "interfaces": { "google.cloud.securitycenter.v1p1beta1.SecurityCenter": { "retry_codes": { - "idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], - "non_idempotent": [], + "retry_policy_1_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], + "no_retry_2_codes": [], + "no_retry_codes": [], + "retry_policy_2_codes": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], + "no_retry_1_codes": [], }, "retry_params": { - "default": { + "retry_policy_1_params": { "initial_retry_delay_millis": 100, "retry_delay_multiplier": 1.3, "max_retry_delay_millis": 60000, - "initial_rpc_timeout_millis": 20000, + "initial_rpc_timeout_millis": 60000, "rpc_timeout_multiplier": 1.0, - "max_rpc_timeout_millis": 20000, - "total_timeout_millis": 600000, - } + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 60000, + }, + "retry_policy_2_params": { + "initial_retry_delay_millis": 100, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 60000, + "initial_rpc_timeout_millis": 480000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 480000, + "total_timeout_millis": 480000, + }, + "no_retry_params": { + "initial_retry_delay_millis": 0, + "retry_delay_multiplier": 0.0, + "max_retry_delay_millis": 0, + "initial_rpc_timeout_millis": 0, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 0, + "total_timeout_millis": 0, + }, + "no_retry_1_params": { + "initial_retry_delay_millis": 0, + "retry_delay_multiplier": 0.0, + "max_retry_delay_millis": 0, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 60000, + }, + "no_retry_2_params": { + "initial_retry_delay_millis": 0, + "retry_delay_multiplier": 0.0, + "max_retry_delay_millis": 0, + "initial_rpc_timeout_millis": 480000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 480000, + "total_timeout_millis": 480000, + }, }, "methods": { "CreateSource": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "CreateFinding": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "CreateNotificationConfig": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "DeleteNotificationConfig": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "GetIamPolicy": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "GetNotificationConfig": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "GetOrganizationSettings": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "GetSource": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "GroupAssets": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "timeout_millis": 480000, + "retry_codes_name": "retry_policy_2_codes", + "retry_params_name": "retry_policy_2_params", }, "GroupFindings": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "timeout_millis": 480000, + "retry_codes_name": "retry_policy_2_codes", + "retry_params_name": "retry_policy_2_params", }, "ListAssets": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "timeout_millis": 480000, + "retry_codes_name": "retry_policy_2_codes", + "retry_params_name": "retry_policy_2_params", }, "ListFindings": { - "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "timeout_millis": 480000, + "retry_codes_name": "retry_policy_2_codes", + "retry_params_name": "retry_policy_2_params", }, "ListNotificationConfigs": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "ListSources": { "timeout_millis": 60000, - "retry_codes_name": "idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "RunAssetDiscovery": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "SetFindingState": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "SetIamPolicy": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "TestIamPermissions": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "retry_policy_1_codes", + "retry_params_name": "retry_policy_1_params", }, "UpdateFinding": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "UpdateNotificationConfig": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "UpdateOrganizationSettings": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "UpdateSource": { "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "retry_codes_name": "no_retry_1_codes", + "retry_params_name": "no_retry_1_params", }, "UpdateSecurityMarks": { - "timeout_millis": 60000, - "retry_codes_name": "non_idempotent", - "retry_params_name": "default", + "timeout_millis": 480000, + "retry_codes_name": "no_retry_2_codes", + "retry_params_name": "no_retry_2_params", }, }, } diff --git a/google/cloud/securitycenter_v1p1beta1/proto/asset_pb2.py b/google/cloud/securitycenter_v1p1beta1/proto/asset_pb2.py index 17685d49..7279b30b 100644 --- a/google/cloud/securitycenter_v1p1beta1/proto/asset_pb2.py +++ b/google/cloud/securitycenter_v1p1beta1/proto/asset_pb2.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/securitycenter_v1p1beta1/proto/asset.proto - +"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection diff --git a/google/cloud/securitycenter_v1p1beta1/proto/finding.proto b/google/cloud/securitycenter_v1p1beta1/proto/finding.proto index 21b65536..49f8159f 100644 --- a/google/cloud/securitycenter_v1p1beta1/proto/finding.proto +++ b/google/cloud/securitycenter_v1p1beta1/proto/finding.proto @@ -55,6 +55,24 @@ message Finding { INACTIVE = 2; } + // The severity of the finding. + enum Severity { + // No severity specified. The default value. + SEVERITY_UNSPECIFIED = 0; + + // Critical severity. + CRITICAL = 1; + + // High severity. + HIGH = 2; + + // Medium severity. + MEDIUM = 3; + + // Low severity. + LOW = 4; + } + // The relative resource name of this finding. See: // https://cloud.google.com/apis/design/resource_names#relative_resource_name // Example: @@ -100,11 +118,16 @@ message Finding { // to the finding. SecurityMarks security_marks = 8 [(google.api.field_behavior) = OUTPUT_ONLY]; - // The time at which the event took place. For example, if the finding - // represents an open firewall it would capture the time the detector believes - // the firewall became open. The accuracy is determined by the detector. + // The time at which the event took place, or when an update to the finding + // occurred. For example, if the finding represents an open firewall it would + // capture the time the detector believes the firewall became open. The + // accuracy is determined by the detector. If the finding were to be resolved + // afterward, this time would reflect when the finding was resolved. google.protobuf.Timestamp event_time = 9; // The time at which the finding was created in Security Command Center. google.protobuf.Timestamp create_time = 10; + + // The severity of the finding. + Severity severity = 13; } diff --git a/google/cloud/securitycenter_v1p1beta1/proto/finding_pb2.py b/google/cloud/securitycenter_v1p1beta1/proto/finding_pb2.py index 84acbbfe..97dc7485 100644 --- a/google/cloud/securitycenter_v1p1beta1/proto/finding_pb2.py +++ b/google/cloud/securitycenter_v1p1beta1/proto/finding_pb2.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/securitycenter_v1p1beta1/proto/finding.proto - +"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection @@ -28,7 +28,7 @@ syntax="proto3", serialized_options=b"\n)com.google.cloud.securitycenter.v1p1beta1P\001ZSgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1;securitycenter\252\002%Google.Cloud.SecurityCenter.V1P1Beta1\312\002%Google\\Cloud\\SecurityCenter\\V1p1beta1\352\002(Google::Cloud::SecurityCenter::V1p1beta1", create_key=_descriptor._internal_create_key, - serialized_pb=b'\n9google/cloud/securitycenter_v1p1beta1/proto/finding.proto\x12%google.cloud.securitycenter.v1p1beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a@google/cloud/securitycenter_v1p1beta1/proto/security_marks.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\xb9\x05\n\x07\x46inding\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06parent\x18\x02 \x01(\t\x12\x15\n\rresource_name\x18\x03 \x01(\t\x12\x43\n\x05state\x18\x04 \x01(\x0e\x32\x34.google.cloud.securitycenter.v1p1beta1.Finding.State\x12\x10\n\x08\x63\x61tegory\x18\x05 \x01(\t\x12\x14\n\x0c\x65xternal_uri\x18\x06 \x01(\t\x12_\n\x11source_properties\x18\x07 \x03(\x0b\x32\x44.google.cloud.securitycenter.v1p1beta1.Finding.SourcePropertiesEntry\x12Q\n\x0esecurity_marks\x18\x08 \x01(\x0b\x32\x34.google.cloud.securitycenter.v1p1beta1.SecurityMarksB\x03\xe0\x41\x03\x12.\n\nevent_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0b\x63reate_time\x18\n \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x1aO\n\x15SourcePropertiesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12%\n\x05value\x18\x02 \x01(\x0b\x32\x16.google.protobuf.Value:\x02\x38\x01"8\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\n\n\x06\x41\x43TIVE\x10\x01\x12\x0c\n\x08INACTIVE\x10\x02:l\xea\x41i\n%securitycenter.googleapis.com/Finding\x12@organizations/{organization}/sources/{source}/findings/{finding}B\xfd\x01\n)com.google.cloud.securitycenter.v1p1beta1P\x01ZSgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1;securitycenter\xaa\x02%Google.Cloud.SecurityCenter.V1P1Beta1\xca\x02%Google\\Cloud\\SecurityCenter\\V1p1beta1\xea\x02(Google::Cloud::SecurityCenter::V1p1beta1b\x06proto3', + serialized_pb=b'\n9google/cloud/securitycenter_v1p1beta1/proto/finding.proto\x12%google.cloud.securitycenter.v1p1beta1\x1a\x1cgoogle/api/annotations.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a@google/cloud/securitycenter_v1p1beta1/proto/security_marks.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\xd7\x06\n\x07\x46inding\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06parent\x18\x02 \x01(\t\x12\x15\n\rresource_name\x18\x03 \x01(\t\x12\x43\n\x05state\x18\x04 \x01(\x0e\x32\x34.google.cloud.securitycenter.v1p1beta1.Finding.State\x12\x10\n\x08\x63\x61tegory\x18\x05 \x01(\t\x12\x14\n\x0c\x65xternal_uri\x18\x06 \x01(\t\x12_\n\x11source_properties\x18\x07 \x03(\x0b\x32\x44.google.cloud.securitycenter.v1p1beta1.Finding.SourcePropertiesEntry\x12Q\n\x0esecurity_marks\x18\x08 \x01(\x0b\x32\x34.google.cloud.securitycenter.v1p1beta1.SecurityMarksB\x03\xe0\x41\x03\x12.\n\nevent_time\x18\t \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0b\x63reate_time\x18\n \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12I\n\x08severity\x18\r \x01(\x0e\x32\x37.google.cloud.securitycenter.v1p1beta1.Finding.Severity\x1aO\n\x15SourcePropertiesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12%\n\x05value\x18\x02 \x01(\x0b\x32\x16.google.protobuf.Value:\x02\x38\x01"8\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\n\n\x06\x41\x43TIVE\x10\x01\x12\x0c\n\x08INACTIVE\x10\x02"Q\n\x08Severity\x12\x18\n\x14SEVERITY_UNSPECIFIED\x10\x00\x12\x0c\n\x08\x43RITICAL\x10\x01\x12\x08\n\x04HIGH\x10\x02\x12\n\n\x06MEDIUM\x10\x03\x12\x07\n\x03LOW\x10\x04:l\xea\x41i\n%securitycenter.googleapis.com/Finding\x12@organizations/{organization}/sources/{source}/findings/{finding}B\xfd\x01\n)com.google.cloud.securitycenter.v1p1beta1P\x01ZSgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1;securitycenter\xaa\x02%Google.Cloud.SecurityCenter.V1P1Beta1\xca\x02%Google\\Cloud\\SecurityCenter\\V1p1beta1\xea\x02(Google::Cloud::SecurityCenter::V1p1beta1b\x06proto3', dependencies=[ google_dot_api_dot_annotations__pb2.DESCRIPTOR, google_dot_api_dot_field__behavior__pb2.DESCRIPTOR, @@ -74,11 +74,66 @@ ], containing_type=None, serialized_options=None, - serialized_start=851, - serialized_end=907, + serialized_start=926, + serialized_end=982, ) _sym_db.RegisterEnumDescriptor(_FINDING_STATE) +_FINDING_SEVERITY = _descriptor.EnumDescriptor( + name="Severity", + full_name="google.cloud.securitycenter.v1p1beta1.Finding.Severity", + filename=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + values=[ + _descriptor.EnumValueDescriptor( + name="SEVERITY_UNSPECIFIED", + index=0, + number=0, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key, + ), + _descriptor.EnumValueDescriptor( + name="CRITICAL", + index=1, + number=1, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key, + ), + _descriptor.EnumValueDescriptor( + name="HIGH", + index=2, + number=2, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key, + ), + _descriptor.EnumValueDescriptor( + name="MEDIUM", + index=3, + number=3, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key, + ), + _descriptor.EnumValueDescriptor( + name="LOW", + index=4, + number=4, + serialized_options=None, + type=None, + create_key=_descriptor._internal_create_key, + ), + ], + containing_type=None, + serialized_options=None, + serialized_start=984, + serialized_end=1065, +) +_sym_db.RegisterEnumDescriptor(_FINDING_SEVERITY) + _FINDING_SOURCEPROPERTIESENTRY = _descriptor.Descriptor( name="SourcePropertiesEntry", @@ -135,8 +190,8 @@ syntax="proto3", extension_ranges=[], oneofs=[], - serialized_start=770, - serialized_end=849, + serialized_start=845, + serialized_end=924, ) _FINDING = _descriptor.Descriptor( @@ -337,17 +392,36 @@ file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), + _descriptor.FieldDescriptor( + name="severity", + full_name="google.cloud.securitycenter.v1p1beta1.Finding.severity", + index=10, + number=13, + type=14, + cpp_type=8, + label=1, + has_default_value=False, + default_value=0, + message_type=None, + enum_type=None, + containing_type=None, + is_extension=False, + extension_scope=None, + serialized_options=None, + file=DESCRIPTOR, + create_key=_descriptor._internal_create_key, + ), ], extensions=[], nested_types=[_FINDING_SOURCEPROPERTIESENTRY,], - enum_types=[_FINDING_STATE,], + enum_types=[_FINDING_STATE, _FINDING_SEVERITY,], serialized_options=b"\352Ai\n%securitycenter.googleapis.com/Finding\022@organizations/{organization}/sources/{source}/findings/{finding}", is_extendable=False, syntax="proto3", extension_ranges=[], oneofs=[], serialized_start=320, - serialized_end=1017, + serialized_end=1175, ) _FINDING_SOURCEPROPERTIESENTRY.fields_by_name[ @@ -369,7 +443,9 @@ _FINDING.fields_by_name[ "create_time" ].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP +_FINDING.fields_by_name["severity"].enum_type = _FINDING_SEVERITY _FINDING_STATE.containing_type = _FINDING +_FINDING_SEVERITY.containing_type = _FINDING DESCRIPTOR.message_types_by_name["Finding"] = _FINDING _sym_db.RegisterFileDescriptor(DESCRIPTOR) @@ -435,13 +511,17 @@ entirely managed by the user and come from the SecurityMarks resource that belongs to the finding. event_time: - The time at which the event took place. For example, if the - finding represents an open firewall it would capture the time - the detector believes the firewall became open. The accuracy - is determined by the detector. + The time at which the event took place, or when an update to + the finding occurred. For example, if the finding represents + an open firewall it would capture the time the detector + believes the firewall became open. The accuracy is determined + by the detector. If the finding were to be resolved afterward, + this time would reflect when the finding was resolved. create_time: The time at which the finding was created in Security Command Center. + severity: + The severity of the finding. """, # @@protoc_insertion_point(class_scope:google.cloud.securitycenter.v1p1beta1.Finding) }, diff --git a/google/cloud/securitycenter_v1p1beta1/proto/notification_config_pb2.py b/google/cloud/securitycenter_v1p1beta1/proto/notification_config_pb2.py index 9564eaaa..8bbd4f58 100644 --- a/google/cloud/securitycenter_v1p1beta1/proto/notification_config_pb2.py +++ b/google/cloud/securitycenter_v1p1beta1/proto/notification_config_pb2.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/securitycenter_v1p1beta1/proto/notification_config.proto - +"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection diff --git a/google/cloud/securitycenter_v1p1beta1/proto/notification_message_pb2.py b/google/cloud/securitycenter_v1p1beta1/proto/notification_message_pb2.py index 3d43d832..ad130b54 100644 --- a/google/cloud/securitycenter_v1p1beta1/proto/notification_message_pb2.py +++ b/google/cloud/securitycenter_v1p1beta1/proto/notification_message_pb2.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/securitycenter_v1p1beta1/proto/notification_message.proto - +"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection diff --git a/google/cloud/securitycenter_v1p1beta1/proto/organization_settings_pb2.py b/google/cloud/securitycenter_v1p1beta1/proto/organization_settings_pb2.py index 83e3bca4..544781d4 100644 --- a/google/cloud/securitycenter_v1p1beta1/proto/organization_settings_pb2.py +++ b/google/cloud/securitycenter_v1p1beta1/proto/organization_settings_pb2.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/securitycenter_v1p1beta1/proto/organization_settings.proto - +"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection diff --git a/google/cloud/securitycenter_v1p1beta1/proto/resource_pb2.py b/google/cloud/securitycenter_v1p1beta1/proto/resource_pb2.py index b44b1fc9..8ed3294f 100644 --- a/google/cloud/securitycenter_v1p1beta1/proto/resource_pb2.py +++ b/google/cloud/securitycenter_v1p1beta1/proto/resource_pb2.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/securitycenter_v1p1beta1/proto/resource.proto - +"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection diff --git a/google/cloud/securitycenter_v1p1beta1/proto/run_asset_discovery_response_pb2.py b/google/cloud/securitycenter_v1p1beta1/proto/run_asset_discovery_response_pb2.py index 33099e91..a2657770 100644 --- a/google/cloud/securitycenter_v1p1beta1/proto/run_asset_discovery_response_pb2.py +++ b/google/cloud/securitycenter_v1p1beta1/proto/run_asset_discovery_response_pb2.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/securitycenter_v1p1beta1/proto/run_asset_discovery_response.proto - +"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection diff --git a/google/cloud/securitycenter_v1p1beta1/proto/security_marks_pb2.py b/google/cloud/securitycenter_v1p1beta1/proto/security_marks_pb2.py index d8d0db24..76a7c221 100644 --- a/google/cloud/securitycenter_v1p1beta1/proto/security_marks_pb2.py +++ b/google/cloud/securitycenter_v1p1beta1/proto/security_marks_pb2.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/securitycenter_v1p1beta1/proto/security_marks.proto - +"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection diff --git a/google/cloud/securitycenter_v1p1beta1/proto/securitycenter_service.proto b/google/cloud/securitycenter_v1p1beta1/proto/securitycenter_service.proto index c4264a6a..69d864c6 100644 --- a/google/cloud/securitycenter_v1p1beta1/proto/securitycenter_service.proto +++ b/google/cloud/securitycenter_v1p1beta1/proto/securitycenter_service.proto @@ -17,7 +17,6 @@ syntax = "proto3"; package google.cloud.securitycenter.v1p1beta1; import public "google/cloud/securitycenter/v1p1beta1/run_asset_discovery_response.proto"; - import "google/api/annotations.proto"; import "google/api/client.proto"; import "google/api/field_behavior.proto"; @@ -47,8 +46,7 @@ option ruby_package = "Google::Cloud::SecurityCenter::V1p1beta1"; // V1p1Beta1 APIs for Security Center service. service SecurityCenter { option (google.api.default_host) = "securitycenter.googleapis.com"; - option (google.api.oauth_scopes) = - "https://www.googleapis.com/auth/cloud-platform"; + option (google.api.oauth_scopes) = "https://www.googleapis.com/auth/cloud-platform"; // Creates a source. rpc CreateSource(CreateSourceRequest) returns (Source) { @@ -59,7 +57,6 @@ service SecurityCenter { option (google.api.method_signature) = "parent,source"; } - // // Creates a finding. The corresponding source must exist for finding // creation to succeed. rpc CreateFinding(CreateFindingRequest) returns (Finding) { @@ -72,20 +69,17 @@ service SecurityCenter { } // Creates a notification config. - rpc CreateNotificationConfig(CreateNotificationConfigRequest) - returns (NotificationConfig) { + rpc CreateNotificationConfig(CreateNotificationConfigRequest) returns (NotificationConfig) { option (google.api.http) = { post: "/v1p1beta1/{parent=organizations/*}/notificationConfigs" body: "notification_config" }; - option (google.api.method_signature) = - "parent,config_id,notification_config"; + option (google.api.method_signature) = "parent,config_id,notification_config"; option (google.api.method_signature) = "parent,notification_config"; } // Deletes a notification config. - rpc DeleteNotificationConfig(DeleteNotificationConfigRequest) - returns (google.protobuf.Empty) { + rpc DeleteNotificationConfig(DeleteNotificationConfigRequest) returns (google.protobuf.Empty) { option (google.api.http) = { delete: "/v1p1beta1/{name=organizations/*/notificationConfigs/*}" }; @@ -93,8 +87,7 @@ service SecurityCenter { } // Gets the access control policy on the specified Source. - rpc GetIamPolicy(google.iam.v1.GetIamPolicyRequest) - returns (google.iam.v1.Policy) { + rpc GetIamPolicy(google.iam.v1.GetIamPolicyRequest) returns (google.iam.v1.Policy) { option (google.api.http) = { post: "/v1p1beta1/{resource=organizations/*/sources/*}:getIamPolicy" body: "*" @@ -103,8 +96,7 @@ service SecurityCenter { } // Gets a notification config. - rpc GetNotificationConfig(GetNotificationConfigRequest) - returns (NotificationConfig) { + rpc GetNotificationConfig(GetNotificationConfigRequest) returns (NotificationConfig) { option (google.api.http) = { get: "/v1p1beta1/{name=organizations/*/notificationConfigs/*}" }; @@ -112,8 +104,7 @@ service SecurityCenter { } // Gets the settings for an organization. - rpc GetOrganizationSettings(GetOrganizationSettingsRequest) - returns (OrganizationSettings) { + rpc GetOrganizationSettings(GetOrganizationSettingsRequest) returns (OrganizationSettings) { option (google.api.http) = { get: "/v1p1beta1/{name=organizations/*/organizationSettings}" }; @@ -170,8 +161,7 @@ service SecurityCenter { } // Lists notification configs. - rpc ListNotificationConfigs(ListNotificationConfigsRequest) - returns (ListNotificationConfigsResponse) { + rpc ListNotificationConfigs(ListNotificationConfigsRequest) returns (ListNotificationConfigsResponse) { option (google.api.http) = { get: "/v1p1beta1/{parent=organizations/*}/notificationConfigs" }; @@ -192,8 +182,7 @@ service SecurityCenter { // This API can only be called with limited frequency for an organization. If // it is called too frequently the caller will receive a TOO_MANY_REQUESTS // error. - rpc RunAssetDiscovery(RunAssetDiscoveryRequest) - returns (google.longrunning.Operation) { + rpc RunAssetDiscovery(RunAssetDiscoveryRequest) returns (google.longrunning.Operation) { option (google.api.http) = { post: "/v1p1beta1/{parent=organizations/*}/assets:runDiscovery" body: "*" @@ -205,7 +194,6 @@ service SecurityCenter { }; } - // // Updates the state of a finding. rpc SetFindingState(SetFindingStateRequest) returns (Finding) { option (google.api.http) = { @@ -216,8 +204,7 @@ service SecurityCenter { } // Sets the access control policy on the specified Source. - rpc SetIamPolicy(google.iam.v1.SetIamPolicyRequest) - returns (google.iam.v1.Policy) { + rpc SetIamPolicy(google.iam.v1.SetIamPolicyRequest) returns (google.iam.v1.Policy) { option (google.api.http) = { post: "/v1p1beta1/{resource=organizations/*/sources/*}:setIamPolicy" body: "*" @@ -226,8 +213,7 @@ service SecurityCenter { } // Returns the permissions that a caller has on the specified source. - rpc TestIamPermissions(google.iam.v1.TestIamPermissionsRequest) - returns (google.iam.v1.TestIamPermissionsResponse) { + rpc TestIamPermissions(google.iam.v1.TestIamPermissionsRequest) returns (google.iam.v1.TestIamPermissionsResponse) { option (google.api.http) = { post: "/v1p1beta1/{resource=organizations/*/sources/*}:testIamPermissions" body: "*" @@ -248,8 +234,7 @@ service SecurityCenter { // Updates a notification config. The following update // fields are allowed: description, pubsub_topic, streaming_config.filter - rpc UpdateNotificationConfig(UpdateNotificationConfigRequest) - returns (NotificationConfig) { + rpc UpdateNotificationConfig(UpdateNotificationConfigRequest) returns (NotificationConfig) { option (google.api.http) = { patch: "/v1p1beta1/{notification_config.name=organizations/*/notificationConfigs/*}" body: "notification_config" @@ -259,8 +244,7 @@ service SecurityCenter { } // Updates an organization's settings. - rpc UpdateOrganizationSettings(UpdateOrganizationSettingsRequest) - returns (OrganizationSettings) { + rpc UpdateOrganizationSettings(UpdateOrganizationSettingsRequest) returns (OrganizationSettings) { option (google.api.http) = { patch: "/v1p1beta1/{organization_settings.name=organizations/*/organizationSettings}" body: "organization_settings" @@ -305,19 +289,17 @@ message CreateFindingRequest { ]; // Required. Unique identifier provided by the client within the parent scope. - // It must be alphanumeric and less than or equal to 32 characters and - // greater than 0 characters in length. string finding_id = 2 [(google.api.field_behavior) = REQUIRED]; - // Required. The Finding being created. The name and security_marks will be - // ignored as they are both output only fields on this resource. + // Required. The Finding being created. The name and security_marks will be ignored as + // they are both output only fields on this resource. Finding finding = 3 [(google.api.field_behavior) = REQUIRED]; } // Request message for creating a notification config. message CreateNotificationConfigRequest { - // Required. Resource name of the new notification config's parent. Its format - // is "organizations/[organization_id]". + // Required. Resource name of the new notification config's parent. Its format is + // "organizations/[organization_id]". string parent = 1 [ (google.api.field_behavior) = REQUIRED, (google.api.resource_reference) = { @@ -331,11 +313,9 @@ message CreateNotificationConfigRequest { // characters, underscores or hyphens only. string config_id = 2 [(google.api.field_behavior) = REQUIRED]; - // Required. The notification config being created. The name and the service - // account will be ignored as they are both output only fields on this - // resource. - NotificationConfig notification_config = 3 - [(google.api.field_behavior) = REQUIRED]; + // Required. The notification config being created. The name and the service account + // will be ignored as they are both output only fields on this resource. + NotificationConfig notification_config = 3 [(google.api.field_behavior) = REQUIRED]; } // Request message for creating a source. @@ -349,8 +329,8 @@ message CreateSourceRequest { } ]; - // Required. The Source being created, only the display_name and description - // will be used. All other fields will be ignored. + // Required. The Source being created, only the display_name and description will be + // used. All other fields will be ignored. Source source = 2 [(google.api.field_behavior) = REQUIRED]; } @@ -380,8 +360,8 @@ message GetNotificationConfigRequest { // Request message for getting organization settings. message GetOrganizationSettingsRequest { - // Required. Name of the organization to get organization settings for. Its - // format is "organizations/[organization_id]/organizationSettings". + // Required. Name of the organization to get organization settings for. Its format is + // "organizations/[organization_id]/organizationSettings". string name = 1 [ (google.api.field_behavior) = REQUIRED, (google.api.resource_reference) = { @@ -477,9 +457,9 @@ message GroupAssetsRequest { // property not existing: `-resource_properties.my_property : ""` string filter = 2; - // Required. Expression that defines what assets fields to use for grouping. - // The string value should follow SQL syntax: comma separated list of fields. - // For example: + // Required. Expression that defines what assets fields to use for grouping. The string + // value should follow SQL syntax: comma separated list of fields. For + // example: // "security_center_properties.resource_project,security_center_properties.project". // // The following fields are supported when compare_duration is not set: @@ -624,9 +604,9 @@ message GroupFindingsRequest { // property not existing: `-source_properties.my_property : ""` string filter = 2; - // Required. Expression that defines what assets fields to use for grouping - // (including `state_change`). The string value should follow SQL syntax: - // comma separated list of fields. For example: "parent,resource_name". + // Required. Expression that defines what assets fields to use for grouping (including + // `state_change`). The string value should follow SQL syntax: comma separated + // list of fields. For example: "parent,resource_name". // // The following fields are supported: // @@ -750,8 +730,8 @@ message ListNotificationConfigsResponse { // Request message for listing sources. message ListSourcesRequest { - // Required. Resource name of the parent of sources to list. Its format should - // be "organizations/[organization_id]". + // Required. Resource name of the parent of sources to list. Its format should be + // "organizations/[organization_id]". string parent = 1 [ (google.api.field_behavior) = REQUIRED, (google.api.resource_reference) = { @@ -909,12 +889,10 @@ message ListAssetsRequest { // read_time. google.protobuf.Duration compare_duration = 5; - // Optional. // A field mask to specify the ListAssetsResult fields to be listed in the // response. // An empty field mask will list all fields. - google.protobuf.FieldMask field_mask = 7 - [(google.api.field_behavior) = OPTIONAL]; + google.protobuf.FieldMask field_mask = 7; // The value returned by the last `ListAssetsResponse`; indicates // that this is a continuation of a prior `ListAssets` call, and @@ -1093,11 +1071,9 @@ message ListFindingsRequest { // read_time. google.protobuf.Duration compare_duration = 5; - // Optional. // A field mask to specify the Finding fields to be listed in the response. // An empty field mask will list all fields. - google.protobuf.FieldMask field_mask = 7 - [(google.api.field_behavior) = OPTIONAL]; + google.protobuf.FieldMask field_mask = 7; // The value returned by the last `ListFindingsResponse`; indicates // that this is a continuation of a prior `ListFindings` call, and @@ -1168,7 +1144,7 @@ message ListFindingsResponse { StateChange state_change = 2; // Output only. Resource that is associated with this finding. - Resource resource = 3; + Resource resource = 3 [(google.api.field_behavior) = OUTPUT_ONLY]; } // Findings matching the list request. @@ -1202,14 +1178,13 @@ message SetFindingStateRequest { Finding.State state = 2 [(google.api.field_behavior) = REQUIRED]; // Required. The time at which the updated state takes effect. - google.protobuf.Timestamp start_time = 3 - [(google.api.field_behavior) = REQUIRED]; + google.protobuf.Timestamp start_time = 3 [(google.api.field_behavior) = REQUIRED]; } // Request message for running asset discovery for an organization. message RunAssetDiscoveryRequest { - // Required. Name of the organization to run asset discovery for. Its format - // is "organizations/[organization_id]". + // Required. Name of the organization to run asset discovery for. Its format is + // "organizations/[organization_id]". string parent = 1 [ (google.api.field_behavior) = REQUIRED, (google.api.resource_reference) = { @@ -1220,8 +1195,8 @@ message RunAssetDiscoveryRequest { // Request message for updating or creating a finding. message UpdateFindingRequest { - // Required. The finding resource to update or create if it does not already - // exist. parent, security_marks, and update_time will be ignored. + // Required. The finding resource to update or create if it does not already exist. + // parent, security_marks, and update_time will be ignored. // // In the case of creation, the finding id portion of the name must be // alphanumeric and less than or equal to 32 characters and greater than 0 @@ -1241,8 +1216,7 @@ message UpdateFindingRequest { // Request message for updating a notification config. message UpdateNotificationConfigRequest { // Required. The notification config to update. - NotificationConfig notification_config = 1 - [(google.api.field_behavior) = REQUIRED]; + NotificationConfig notification_config = 1 [(google.api.field_behavior) = REQUIRED]; // The FieldMask to use when updating the notification config. // @@ -1253,8 +1227,7 @@ message UpdateNotificationConfigRequest { // Request message for updating an organization's settings. message UpdateOrganizationSettingsRequest { // Required. The organization settings resource to update. - OrganizationSettings organization_settings = 1 - [(google.api.field_behavior) = REQUIRED]; + OrganizationSettings organization_settings = 1 [(google.api.field_behavior) = REQUIRED]; // The FieldMask to use when updating the settings resource. // diff --git a/google/cloud/securitycenter_v1p1beta1/proto/securitycenter_service_pb2.py b/google/cloud/securitycenter_v1p1beta1/proto/securitycenter_service_pb2.py index 583e5d79..5a70da84 100644 --- a/google/cloud/securitycenter_v1p1beta1/proto/securitycenter_service_pb2.py +++ b/google/cloud/securitycenter_v1p1beta1/proto/securitycenter_service_pb2.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/securitycenter_v1p1beta1/proto/securitycenter_service.proto - +"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection @@ -56,7 +56,7 @@ syntax="proto3", serialized_options=b"\n)com.google.cloud.securitycenter.v1p1beta1P\001ZSgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1;securitycenter\252\002%Google.Cloud.SecurityCenter.V1P1Beta1\312\002%Google\\Cloud\\SecurityCenter\\V1p1beta1\352\002(Google::Cloud::SecurityCenter::V1p1beta1", create_key=_descriptor._internal_create_key, - serialized_pb=b'\nHgoogle/cloud/securitycenter_v1p1beta1/proto/securitycenter_service.proto\x12%google.cloud.securitycenter.v1p1beta1\x1aNgoogle/cloud/securitycenter_v1p1beta1/proto/run_asset_discovery_response.proto\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a\x37google/cloud/securitycenter_v1p1beta1/proto/asset.proto\x1a\x39google/cloud/securitycenter_v1p1beta1/proto/finding.proto\x1a\x45google/cloud/securitycenter_v1p1beta1/proto/notification_config.proto\x1aGgoogle/cloud/securitycenter_v1p1beta1/proto/organization_settings.proto\x1a@google/cloud/securitycenter_v1p1beta1/proto/security_marks.proto\x1a\x38google/cloud/securitycenter_v1p1beta1/proto/source.proto\x1a\x1egoogle/iam/v1/iam_policy.proto\x1a\x1agoogle/iam/v1/policy.proto\x1a#google/longrunning/operations.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a google/protobuf/field_mask.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\xb3\x01\n\x14\x43reateFindingRequest\x12<\n\x06parent\x18\x01 \x01(\tB,\xe0\x41\x02\xfa\x41&\n$securitycenter.googleapis.com/Source\x12\x17\n\nfinding_id\x18\x02 \x01(\tB\x03\xe0\x41\x02\x12\x44\n\x07\x66inding\x18\x03 \x01(\x0b\x32..google.cloud.securitycenter.v1p1beta1.FindingB\x03\xe0\x41\x02"\xe0\x01\n\x1f\x43reateNotificationConfigRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization\x12\x16\n\tconfig_id\x18\x02 \x01(\tB\x03\xe0\x41\x02\x12[\n\x13notification_config\x18\x03 \x01(\x0b\x32\x39.google.cloud.securitycenter.v1p1beta1.NotificationConfigB\x03\xe0\x41\x02"\xa3\x01\n\x13\x43reateSourceRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization\x12\x42\n\x06source\x18\x02 \x01(\x0b\x32-.google.cloud.securitycenter.v1p1beta1.SourceB\x03\xe0\x41\x02"i\n\x1f\x44\x65leteNotificationConfigRequest\x12\x46\n\x04name\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0securitycenter.googleapis.com/NotificationConfig"f\n\x1cGetNotificationConfigRequest\x12\x46\n\x04name\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0securitycenter.googleapis.com/NotificationConfig"j\n\x1eGetOrganizationSettingsRequest\x12H\n\x04name\x18\x01 \x01(\tB:\xe0\x41\x02\xfa\x41\x34\n2securitycenter.googleapis.com/OrganizationSettings"N\n\x10GetSourceRequest\x12:\n\x04name\x18\x01 \x01(\tB,\xe0\x41\x02\xfa\x41&\n$securitycenter.googleapis.com/Source"\x90\x02\n\x12GroupAssetsRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization\x12\x0e\n\x06\x66ilter\x18\x02 \x01(\t\x12\x15\n\x08group_by\x18\x03 \x01(\tB\x03\xe0\x41\x02\x12\x33\n\x10\x63ompare_duration\x18\x04 \x01(\x0b\x32\x19.google.protobuf.Duration\x12-\n\tread_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x12\n\npage_token\x18\x07 \x01(\t\x12\x11\n\tpage_size\x18\x08 \x01(\x05"\xbf\x01\n\x13GroupAssetsResponse\x12L\n\x10group_by_results\x18\x01 \x03(\x0b\x32\x32.google.cloud.securitycenter.v1p1beta1.GroupResult\x12-\n\tread_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x17\n\x0fnext_page_token\x18\x03 \x01(\t\x12\x12\n\ntotal_size\x18\x04 \x01(\x05"\x86\x02\n\x14GroupFindingsRequest\x12<\n\x06parent\x18\x01 \x01(\tB,\xe0\x41\x02\xfa\x41&\n$securitycenter.googleapis.com/Source\x12\x0e\n\x06\x66ilter\x18\x02 \x01(\t\x12\x15\n\x08group_by\x18\x03 \x01(\tB\x03\xe0\x41\x02\x12-\n\tread_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x33\n\x10\x63ompare_duration\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x12\n\npage_token\x18\x07 \x01(\t\x12\x11\n\tpage_size\x18\x08 \x01(\x05"\xc1\x01\n\x15GroupFindingsResponse\x12L\n\x10group_by_results\x18\x01 \x03(\x0b\x32\x32.google.cloud.securitycenter.v1p1beta1.GroupResult\x12-\n\tread_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x17\n\x0fnext_page_token\x18\x03 \x01(\t\x12\x12\n\ntotal_size\x18\x04 \x01(\x05"\xbf\x01\n\x0bGroupResult\x12V\n\nproperties\x18\x01 \x03(\x0b\x32\x42.google.cloud.securitycenter.v1p1beta1.GroupResult.PropertiesEntry\x12\r\n\x05\x63ount\x18\x02 \x01(\x03\x1aI\n\x0fPropertiesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12%\n\x05value\x18\x02 \x01(\x0b\x32\x16.google.protobuf.Value:\x02\x38\x01"\x91\x01\n\x1eListNotificationConfigsRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization\x12\x12\n\npage_token\x18\x02 \x01(\t\x12\x11\n\tpage_size\x18\x03 \x01(\x05"\x93\x01\n\x1fListNotificationConfigsResponse\x12W\n\x14notification_configs\x18\x01 \x03(\x0b\x32\x39.google.cloud.securitycenter.v1p1beta1.NotificationConfig\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"\x85\x01\n\x12ListSourcesRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization\x12\x12\n\npage_token\x18\x02 \x01(\t\x12\x11\n\tpage_size\x18\x07 \x01(\x05"n\n\x13ListSourcesResponse\x12>\n\x07sources\x18\x01 \x03(\x0b\x32-.google.cloud.securitycenter.v1p1beta1.Source\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"\xbf\x02\n\x11ListAssetsRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization\x12\x0e\n\x06\x66ilter\x18\x02 \x01(\t\x12\x10\n\x08order_by\x18\x03 \x01(\t\x12-\n\tread_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x33\n\x10\x63ompare_duration\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x33\n\nfield_mask\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.FieldMaskB\x03\xe0\x41\x01\x12\x12\n\npage_token\x18\x08 \x01(\t\x12\x11\n\tpage_size\x18\t \x01(\x05"\xd8\x03\n\x12ListAssetsResponse\x12g\n\x13list_assets_results\x18\x01 \x03(\x0b\x32J.google.cloud.securitycenter.v1p1beta1.ListAssetsResponse.ListAssetsResult\x12-\n\tread_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x17\n\x0fnext_page_token\x18\x03 \x01(\t\x12\x12\n\ntotal_size\x18\x04 \x01(\x05\x1a\xfc\x01\n\x10ListAssetsResult\x12;\n\x05\x61sset\x18\x01 \x01(\x0b\x32,.google.cloud.securitycenter.v1p1beta1.Asset\x12l\n\x0cstate_change\x18\x02 \x01(\x0e\x32V.google.cloud.securitycenter.v1p1beta1.ListAssetsResponse.ListAssetsResult.StateChange"=\n\x0bStateChange\x12\n\n\x06UNUSED\x10\x00\x12\t\n\x05\x41\x44\x44\x45\x44\x10\x01\x12\x0b\n\x07REMOVED\x10\x02\x12\n\n\x06\x41\x43TIVE\x10\x03"\xb5\x02\n\x13ListFindingsRequest\x12<\n\x06parent\x18\x01 \x01(\tB,\xe0\x41\x02\xfa\x41&\n$securitycenter.googleapis.com/Source\x12\x0e\n\x06\x66ilter\x18\x02 \x01(\t\x12\x10\n\x08order_by\x18\x03 \x01(\t\x12-\n\tread_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x33\n\x10\x63ompare_duration\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x33\n\nfield_mask\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.FieldMaskB\x03\xe0\x41\x01\x12\x12\n\npage_token\x18\x08 \x01(\t\x12\x11\n\tpage_size\x18\t \x01(\x05"\xe5\x05\n\x14ListFindingsResponse\x12m\n\x15list_findings_results\x18\x01 \x03(\x0b\x32N.google.cloud.securitycenter.v1p1beta1.ListFindingsResponse.ListFindingsResult\x12-\n\tread_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x17\n\x0fnext_page_token\x18\x03 \x01(\t\x12\x12\n\ntotal_size\x18\x04 \x01(\x05\x1a\x81\x04\n\x12ListFindingsResult\x12?\n\x07\x66inding\x18\x01 \x01(\x0b\x32..google.cloud.securitycenter.v1p1beta1.Finding\x12p\n\x0cstate_change\x18\x02 \x01(\x0e\x32Z.google.cloud.securitycenter.v1p1beta1.ListFindingsResponse.ListFindingsResult.StateChange\x12i\n\x08resource\x18\x03 \x01(\x0b\x32W.google.cloud.securitycenter.v1p1beta1.ListFindingsResponse.ListFindingsResult.Resource\x1a~\n\x08Resource\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x14\n\x0cproject_name\x18\x02 \x01(\t\x12\x1c\n\x14project_display_name\x18\x03 \x01(\t\x12\x13\n\x0bparent_name\x18\x04 \x01(\t\x12\x1b\n\x13parent_display_name\x18\x05 \x01(\t"M\n\x0bStateChange\x12\n\n\x06UNUSED\x10\x00\x12\x0b\n\x07\x43HANGED\x10\x01\x12\r\n\tUNCHANGED\x10\x02\x12\t\n\x05\x41\x44\x44\x45\x44\x10\x03\x12\x0b\n\x07REMOVED\x10\x04"\xd4\x01\n\x16SetFindingStateRequest\x12;\n\x04name\x18\x01 \x01(\tB-\xe0\x41\x02\xfa\x41\'\n%securitycenter.googleapis.com/Finding\x12H\n\x05state\x18\x02 \x01(\x0e\x32\x34.google.cloud.securitycenter.v1p1beta1.Finding.StateB\x03\xe0\x41\x02\x12\x33\n\nstart_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.TimestampB\x03\xe0\x41\x02"d\n\x18RunAssetDiscoveryRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization"\x8d\x01\n\x14UpdateFindingRequest\x12\x44\n\x07\x66inding\x18\x01 \x01(\x0b\x32..google.cloud.securitycenter.v1p1beta1.FindingB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask"\xaf\x01\n\x1fUpdateNotificationConfigRequest\x12[\n\x13notification_config\x18\x01 \x01(\x0b\x32\x39.google.cloud.securitycenter.v1p1beta1.NotificationConfigB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask"\xb5\x01\n!UpdateOrganizationSettingsRequest\x12_\n\x15organization_settings\x18\x01 \x01(\x0b\x32;.google.cloud.securitycenter.v1p1beta1.OrganizationSettingsB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask"\x8a\x01\n\x13UpdateSourceRequest\x12\x42\n\x06source\x18\x01 \x01(\x0b\x32-.google.cloud.securitycenter.v1p1beta1.SourceB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask"\xd0\x01\n\x1aUpdateSecurityMarksRequest\x12Q\n\x0esecurity_marks\x18\x01 \x01(\x0b\x32\x34.google.cloud.securitycenter.v1p1beta1.SecurityMarksB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask\x12.\n\nstart_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp2\x86+\n\x0eSecurityCenter\x12\xc6\x01\n\x0c\x43reateSource\x12:.google.cloud.securitycenter.v1p1beta1.CreateSourceRequest\x1a-.google.cloud.securitycenter.v1p1beta1.Source"K\x82\xd3\xe4\x93\x02\x35"+/v1p1beta1/{parent=organizations/*}/sources:\x06source\xda\x41\rparent,source\x12\xfd\x01\n\rCreateFinding\x12;.google.cloud.securitycenter.v1p1beta1.CreateFindingRequest\x1a..google.cloud.securitycenter.v1p1beta1.Finding"\x7f\x82\xd3\xe4\x93\x02\x41"6/v1p1beta1/{parent=organizations/*/sources/*}/findings:\x07\x66inding\xda\x41\x19parent,finding_id,finding\xda\x41\x19parent,finding,finding_id\x12\xb8\x02\n\x18\x43reateNotificationConfig\x12\x46.google.cloud.securitycenter.v1p1beta1.CreateNotificationConfigRequest\x1a\x39.google.cloud.securitycenter.v1p1beta1.NotificationConfig"\x98\x01\x82\xd3\xe4\x93\x02N"7/v1p1beta1/{parent=organizations/*}/notificationConfigs:\x13notification_config\xda\x41$parent,config_id,notification_config\xda\x41\x1aparent,notification_config\x12\xc2\x01\n\x18\x44\x65leteNotificationConfig\x12\x46.google.cloud.securitycenter.v1p1beta1.DeleteNotificationConfigRequest\x1a\x16.google.protobuf.Empty"F\x82\xd3\xe4\x93\x02\x39*7/v1p1beta1/{name=organizations/*/notificationConfigs/*}\xda\x41\x04name\x12\x9d\x01\n\x0cGetIamPolicy\x12".google.iam.v1.GetIamPolicyRequest\x1a\x15.google.iam.v1.Policy"R\x82\xd3\xe4\x93\x02\x41"/v1p1beta1/{finding.name=organizations/*/sources/*/findings/*}:\x07\x66inding\xda\x41\x07\x66inding\xda\x41\x13\x66inding,update_mask\x12\xc0\x02\n\x18UpdateNotificationConfig\x12\x46.google.cloud.securitycenter.v1p1beta1.UpdateNotificationConfigRequest\x1a\x39.google.cloud.securitycenter.v1p1beta1.NotificationConfig"\xa0\x01\x82\xd3\xe4\x93\x02\x62\x32K/v1p1beta1/{notification_config.name=organizations/*/notificationConfigs/*}:\x13notification_config\xda\x41\x13notification_config\xda\x41\x1fnotification_config,update_mask\x12\xa9\x02\n\x1aUpdateOrganizationSettings\x12H.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest\x1a;.google.cloud.securitycenter.v1p1beta1.OrganizationSettings"\x83\x01\x82\xd3\xe4\x93\x02\x65\x32L/v1p1beta1/{organization_settings.name=organizations/*/organizationSettings}:\x15organization_settings\xda\x41\x15organization_settings\x12\xdb\x01\n\x0cUpdateSource\x12:.google.cloud.securitycenter.v1p1beta1.UpdateSourceRequest\x1a-.google.cloud.securitycenter.v1p1beta1.Source"`\x82\xd3\xe4\x93\x02<22/v1p1beta1/{source.name=organizations/*/sources/*}:\x06source\xda\x41\x06source\xda\x41\x12source,update_mask\x12\x86\x03\n\x13UpdateSecurityMarks\x12\x41.google.cloud.securitycenter.v1p1beta1.UpdateSecurityMarksRequest\x1a\x34.google.cloud.securitycenter.v1p1beta1.SecurityMarks"\xf5\x01\x82\xd3\xe4\x93\x02\xc0\x01\x32G/v1p1beta1/{security_marks.name=organizations/*/assets/*/securityMarks}:\x0esecurity_marksZe2S/v1p1beta1/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}:\x0esecurity_marks\xda\x41\x0esecurity_marks\xda\x41\x1asecurity_marks,update_mask\x1aQ\xca\x41\x1dsecuritycenter.googleapis.com\xd2\x41.https://www.googleapis.com/auth/cloud-platformB\xfd\x01\n)com.google.cloud.securitycenter.v1p1beta1P\x01ZSgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1;securitycenter\xaa\x02%Google.Cloud.SecurityCenter.V1P1Beta1\xca\x02%Google\\Cloud\\SecurityCenter\\V1p1beta1\xea\x02(Google::Cloud::SecurityCenter::V1p1beta1P\x00\x62\x06proto3', + serialized_pb=b'\nHgoogle/cloud/securitycenter_v1p1beta1/proto/securitycenter_service.proto\x12%google.cloud.securitycenter.v1p1beta1\x1aNgoogle/cloud/securitycenter_v1p1beta1/proto/run_asset_discovery_response.proto\x1a\x1cgoogle/api/annotations.proto\x1a\x17google/api/client.proto\x1a\x1fgoogle/api/field_behavior.proto\x1a\x19google/api/resource.proto\x1a\x37google/cloud/securitycenter_v1p1beta1/proto/asset.proto\x1a\x39google/cloud/securitycenter_v1p1beta1/proto/finding.proto\x1a\x45google/cloud/securitycenter_v1p1beta1/proto/notification_config.proto\x1aGgoogle/cloud/securitycenter_v1p1beta1/proto/organization_settings.proto\x1a@google/cloud/securitycenter_v1p1beta1/proto/security_marks.proto\x1a\x38google/cloud/securitycenter_v1p1beta1/proto/source.proto\x1a\x1egoogle/iam/v1/iam_policy.proto\x1a\x1agoogle/iam/v1/policy.proto\x1a#google/longrunning/operations.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a google/protobuf/field_mask.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto"\xb3\x01\n\x14\x43reateFindingRequest\x12<\n\x06parent\x18\x01 \x01(\tB,\xe0\x41\x02\xfa\x41&\n$securitycenter.googleapis.com/Source\x12\x17\n\nfinding_id\x18\x02 \x01(\tB\x03\xe0\x41\x02\x12\x44\n\x07\x66inding\x18\x03 \x01(\x0b\x32..google.cloud.securitycenter.v1p1beta1.FindingB\x03\xe0\x41\x02"\xe0\x01\n\x1f\x43reateNotificationConfigRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization\x12\x16\n\tconfig_id\x18\x02 \x01(\tB\x03\xe0\x41\x02\x12[\n\x13notification_config\x18\x03 \x01(\x0b\x32\x39.google.cloud.securitycenter.v1p1beta1.NotificationConfigB\x03\xe0\x41\x02"\xa3\x01\n\x13\x43reateSourceRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization\x12\x42\n\x06source\x18\x02 \x01(\x0b\x32-.google.cloud.securitycenter.v1p1beta1.SourceB\x03\xe0\x41\x02"i\n\x1f\x44\x65leteNotificationConfigRequest\x12\x46\n\x04name\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0securitycenter.googleapis.com/NotificationConfig"f\n\x1cGetNotificationConfigRequest\x12\x46\n\x04name\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0securitycenter.googleapis.com/NotificationConfig"j\n\x1eGetOrganizationSettingsRequest\x12H\n\x04name\x18\x01 \x01(\tB:\xe0\x41\x02\xfa\x41\x34\n2securitycenter.googleapis.com/OrganizationSettings"N\n\x10GetSourceRequest\x12:\n\x04name\x18\x01 \x01(\tB,\xe0\x41\x02\xfa\x41&\n$securitycenter.googleapis.com/Source"\x90\x02\n\x12GroupAssetsRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization\x12\x0e\n\x06\x66ilter\x18\x02 \x01(\t\x12\x15\n\x08group_by\x18\x03 \x01(\tB\x03\xe0\x41\x02\x12\x33\n\x10\x63ompare_duration\x18\x04 \x01(\x0b\x32\x19.google.protobuf.Duration\x12-\n\tread_time\x18\x05 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x12\n\npage_token\x18\x07 \x01(\t\x12\x11\n\tpage_size\x18\x08 \x01(\x05"\xbf\x01\n\x13GroupAssetsResponse\x12L\n\x10group_by_results\x18\x01 \x03(\x0b\x32\x32.google.cloud.securitycenter.v1p1beta1.GroupResult\x12-\n\tread_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x17\n\x0fnext_page_token\x18\x03 \x01(\t\x12\x12\n\ntotal_size\x18\x04 \x01(\x05"\x86\x02\n\x14GroupFindingsRequest\x12<\n\x06parent\x18\x01 \x01(\tB,\xe0\x41\x02\xfa\x41&\n$securitycenter.googleapis.com/Source\x12\x0e\n\x06\x66ilter\x18\x02 \x01(\t\x12\x15\n\x08group_by\x18\x03 \x01(\tB\x03\xe0\x41\x02\x12-\n\tread_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x33\n\x10\x63ompare_duration\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration\x12\x12\n\npage_token\x18\x07 \x01(\t\x12\x11\n\tpage_size\x18\x08 \x01(\x05"\xc1\x01\n\x15GroupFindingsResponse\x12L\n\x10group_by_results\x18\x01 \x03(\x0b\x32\x32.google.cloud.securitycenter.v1p1beta1.GroupResult\x12-\n\tread_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x17\n\x0fnext_page_token\x18\x03 \x01(\t\x12\x12\n\ntotal_size\x18\x04 \x01(\x05"\xbf\x01\n\x0bGroupResult\x12V\n\nproperties\x18\x01 \x03(\x0b\x32\x42.google.cloud.securitycenter.v1p1beta1.GroupResult.PropertiesEntry\x12\r\n\x05\x63ount\x18\x02 \x01(\x03\x1aI\n\x0fPropertiesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12%\n\x05value\x18\x02 \x01(\x0b\x32\x16.google.protobuf.Value:\x02\x38\x01"\x91\x01\n\x1eListNotificationConfigsRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization\x12\x12\n\npage_token\x18\x02 \x01(\t\x12\x11\n\tpage_size\x18\x03 \x01(\x05"\x93\x01\n\x1fListNotificationConfigsResponse\x12W\n\x14notification_configs\x18\x01 \x03(\x0b\x32\x39.google.cloud.securitycenter.v1p1beta1.NotificationConfig\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"\x85\x01\n\x12ListSourcesRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization\x12\x12\n\npage_token\x18\x02 \x01(\t\x12\x11\n\tpage_size\x18\x07 \x01(\x05"n\n\x13ListSourcesResponse\x12>\n\x07sources\x18\x01 \x03(\x0b\x32-.google.cloud.securitycenter.v1p1beta1.Source\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t"\xba\x02\n\x11ListAssetsRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization\x12\x0e\n\x06\x66ilter\x18\x02 \x01(\t\x12\x10\n\x08order_by\x18\x03 \x01(\t\x12-\n\tread_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x33\n\x10\x63ompare_duration\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration\x12.\n\nfield_mask\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.FieldMask\x12\x12\n\npage_token\x18\x08 \x01(\t\x12\x11\n\tpage_size\x18\t \x01(\x05"\xd8\x03\n\x12ListAssetsResponse\x12g\n\x13list_assets_results\x18\x01 \x03(\x0b\x32J.google.cloud.securitycenter.v1p1beta1.ListAssetsResponse.ListAssetsResult\x12-\n\tread_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x17\n\x0fnext_page_token\x18\x03 \x01(\t\x12\x12\n\ntotal_size\x18\x04 \x01(\x05\x1a\xfc\x01\n\x10ListAssetsResult\x12;\n\x05\x61sset\x18\x01 \x01(\x0b\x32,.google.cloud.securitycenter.v1p1beta1.Asset\x12l\n\x0cstate_change\x18\x02 \x01(\x0e\x32V.google.cloud.securitycenter.v1p1beta1.ListAssetsResponse.ListAssetsResult.StateChange"=\n\x0bStateChange\x12\n\n\x06UNUSED\x10\x00\x12\t\n\x05\x41\x44\x44\x45\x44\x10\x01\x12\x0b\n\x07REMOVED\x10\x02\x12\n\n\x06\x41\x43TIVE\x10\x03"\xb0\x02\n\x13ListFindingsRequest\x12<\n\x06parent\x18\x01 \x01(\tB,\xe0\x41\x02\xfa\x41&\n$securitycenter.googleapis.com/Source\x12\x0e\n\x06\x66ilter\x18\x02 \x01(\t\x12\x10\n\x08order_by\x18\x03 \x01(\t\x12-\n\tread_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x33\n\x10\x63ompare_duration\x18\x05 \x01(\x0b\x32\x19.google.protobuf.Duration\x12.\n\nfield_mask\x18\x07 \x01(\x0b\x32\x1a.google.protobuf.FieldMask\x12\x12\n\npage_token\x18\x08 \x01(\t\x12\x11\n\tpage_size\x18\t \x01(\x05"\xea\x05\n\x14ListFindingsResponse\x12m\n\x15list_findings_results\x18\x01 \x03(\x0b\x32N.google.cloud.securitycenter.v1p1beta1.ListFindingsResponse.ListFindingsResult\x12-\n\tread_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x17\n\x0fnext_page_token\x18\x03 \x01(\t\x12\x12\n\ntotal_size\x18\x04 \x01(\x05\x1a\x86\x04\n\x12ListFindingsResult\x12?\n\x07\x66inding\x18\x01 \x01(\x0b\x32..google.cloud.securitycenter.v1p1beta1.Finding\x12p\n\x0cstate_change\x18\x02 \x01(\x0e\x32Z.google.cloud.securitycenter.v1p1beta1.ListFindingsResponse.ListFindingsResult.StateChange\x12n\n\x08resource\x18\x03 \x01(\x0b\x32W.google.cloud.securitycenter.v1p1beta1.ListFindingsResponse.ListFindingsResult.ResourceB\x03\xe0\x41\x03\x1a~\n\x08Resource\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x14\n\x0cproject_name\x18\x02 \x01(\t\x12\x1c\n\x14project_display_name\x18\x03 \x01(\t\x12\x13\n\x0bparent_name\x18\x04 \x01(\t\x12\x1b\n\x13parent_display_name\x18\x05 \x01(\t"M\n\x0bStateChange\x12\n\n\x06UNUSED\x10\x00\x12\x0b\n\x07\x43HANGED\x10\x01\x12\r\n\tUNCHANGED\x10\x02\x12\t\n\x05\x41\x44\x44\x45\x44\x10\x03\x12\x0b\n\x07REMOVED\x10\x04"\xd4\x01\n\x16SetFindingStateRequest\x12;\n\x04name\x18\x01 \x01(\tB-\xe0\x41\x02\xfa\x41\'\n%securitycenter.googleapis.com/Finding\x12H\n\x05state\x18\x02 \x01(\x0e\x32\x34.google.cloud.securitycenter.v1p1beta1.Finding.StateB\x03\xe0\x41\x02\x12\x33\n\nstart_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.TimestampB\x03\xe0\x41\x02"d\n\x18RunAssetDiscoveryRequest\x12H\n\x06parent\x18\x01 \x01(\tB8\xe0\x41\x02\xfa\x41\x32\n0cloudresourcemanager.googleapis.com/Organization"\x8d\x01\n\x14UpdateFindingRequest\x12\x44\n\x07\x66inding\x18\x01 \x01(\x0b\x32..google.cloud.securitycenter.v1p1beta1.FindingB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask"\xaf\x01\n\x1fUpdateNotificationConfigRequest\x12[\n\x13notification_config\x18\x01 \x01(\x0b\x32\x39.google.cloud.securitycenter.v1p1beta1.NotificationConfigB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask"\xb5\x01\n!UpdateOrganizationSettingsRequest\x12_\n\x15organization_settings\x18\x01 \x01(\x0b\x32;.google.cloud.securitycenter.v1p1beta1.OrganizationSettingsB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask"\x8a\x01\n\x13UpdateSourceRequest\x12\x42\n\x06source\x18\x01 \x01(\x0b\x32-.google.cloud.securitycenter.v1p1beta1.SourceB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask"\xd0\x01\n\x1aUpdateSecurityMarksRequest\x12Q\n\x0esecurity_marks\x18\x01 \x01(\x0b\x32\x34.google.cloud.securitycenter.v1p1beta1.SecurityMarksB\x03\xe0\x41\x02\x12/\n\x0bupdate_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask\x12.\n\nstart_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp2\x86+\n\x0eSecurityCenter\x12\xc6\x01\n\x0c\x43reateSource\x12:.google.cloud.securitycenter.v1p1beta1.CreateSourceRequest\x1a-.google.cloud.securitycenter.v1p1beta1.Source"K\x82\xd3\xe4\x93\x02\x35"+/v1p1beta1/{parent=organizations/*}/sources:\x06source\xda\x41\rparent,source\x12\xfd\x01\n\rCreateFinding\x12;.google.cloud.securitycenter.v1p1beta1.CreateFindingRequest\x1a..google.cloud.securitycenter.v1p1beta1.Finding"\x7f\x82\xd3\xe4\x93\x02\x41"6/v1p1beta1/{parent=organizations/*/sources/*}/findings:\x07\x66inding\xda\x41\x19parent,finding_id,finding\xda\x41\x19parent,finding,finding_id\x12\xb8\x02\n\x18\x43reateNotificationConfig\x12\x46.google.cloud.securitycenter.v1p1beta1.CreateNotificationConfigRequest\x1a\x39.google.cloud.securitycenter.v1p1beta1.NotificationConfig"\x98\x01\x82\xd3\xe4\x93\x02N"7/v1p1beta1/{parent=organizations/*}/notificationConfigs:\x13notification_config\xda\x41$parent,config_id,notification_config\xda\x41\x1aparent,notification_config\x12\xc2\x01\n\x18\x44\x65leteNotificationConfig\x12\x46.google.cloud.securitycenter.v1p1beta1.DeleteNotificationConfigRequest\x1a\x16.google.protobuf.Empty"F\x82\xd3\xe4\x93\x02\x39*7/v1p1beta1/{name=organizations/*/notificationConfigs/*}\xda\x41\x04name\x12\x9d\x01\n\x0cGetIamPolicy\x12".google.iam.v1.GetIamPolicyRequest\x1a\x15.google.iam.v1.Policy"R\x82\xd3\xe4\x93\x02\x41"/v1p1beta1/{finding.name=organizations/*/sources/*/findings/*}:\x07\x66inding\xda\x41\x07\x66inding\xda\x41\x13\x66inding,update_mask\x12\xc0\x02\n\x18UpdateNotificationConfig\x12\x46.google.cloud.securitycenter.v1p1beta1.UpdateNotificationConfigRequest\x1a\x39.google.cloud.securitycenter.v1p1beta1.NotificationConfig"\xa0\x01\x82\xd3\xe4\x93\x02\x62\x32K/v1p1beta1/{notification_config.name=organizations/*/notificationConfigs/*}:\x13notification_config\xda\x41\x13notification_config\xda\x41\x1fnotification_config,update_mask\x12\xa9\x02\n\x1aUpdateOrganizationSettings\x12H.google.cloud.securitycenter.v1p1beta1.UpdateOrganizationSettingsRequest\x1a;.google.cloud.securitycenter.v1p1beta1.OrganizationSettings"\x83\x01\x82\xd3\xe4\x93\x02\x65\x32L/v1p1beta1/{organization_settings.name=organizations/*/organizationSettings}:\x15organization_settings\xda\x41\x15organization_settings\x12\xdb\x01\n\x0cUpdateSource\x12:.google.cloud.securitycenter.v1p1beta1.UpdateSourceRequest\x1a-.google.cloud.securitycenter.v1p1beta1.Source"`\x82\xd3\xe4\x93\x02<22/v1p1beta1/{source.name=organizations/*/sources/*}:\x06source\xda\x41\x06source\xda\x41\x12source,update_mask\x12\x86\x03\n\x13UpdateSecurityMarks\x12\x41.google.cloud.securitycenter.v1p1beta1.UpdateSecurityMarksRequest\x1a\x34.google.cloud.securitycenter.v1p1beta1.SecurityMarks"\xf5\x01\x82\xd3\xe4\x93\x02\xc0\x01\x32G/v1p1beta1/{security_marks.name=organizations/*/assets/*/securityMarks}:\x0esecurity_marksZe2S/v1p1beta1/{security_marks.name=organizations/*/sources/*/findings/*/securityMarks}:\x0esecurity_marks\xda\x41\x0esecurity_marks\xda\x41\x1asecurity_marks,update_mask\x1aQ\xca\x41\x1dsecuritycenter.googleapis.com\xd2\x41.https://www.googleapis.com/auth/cloud-platformB\xfd\x01\n)com.google.cloud.securitycenter.v1p1beta1P\x01ZSgoogle.golang.org/genproto/googleapis/cloud/securitycenter/v1p1beta1;securitycenter\xaa\x02%Google.Cloud.SecurityCenter.V1P1Beta1\xca\x02%Google\\Cloud\\SecurityCenter\\V1p1beta1\xea\x02(Google::Cloud::SecurityCenter::V1p1beta1P\x00\x62\x06proto3', dependencies=[ google_dot_cloud_dot_securitycenter__v1p1beta1_dot_proto_dot_run__asset__discovery__response__pb2.DESCRIPTOR, google_dot_api_dot_annotations__pb2.DESCRIPTOR, @@ -126,8 +126,8 @@ ], containing_type=None, serialized_options=None, - serialized_start=4327, - serialized_end=4388, + serialized_start=4322, + serialized_end=4383, ) _sym_db.RegisterEnumDescriptor(_LISTASSETSRESPONSE_LISTASSETSRESULT_STATECHANGE) @@ -181,8 +181,8 @@ ], containing_type=None, serialized_options=None, - serialized_start=5367, - serialized_end=5444, + serialized_start=5362, + serialized_end=5439, ) _sym_db.RegisterEnumDescriptor(_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT_STATECHANGE) @@ -1590,7 +1590,7 @@ containing_type=None, is_extension=False, extension_scope=None, - serialized_options=b"\340A\001", + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), @@ -1642,7 +1642,7 @@ extension_ranges=[], oneofs=[], serialized_start=3594, - serialized_end=3913, + serialized_end=3908, ) @@ -1701,8 +1701,8 @@ syntax="proto3", extension_ranges=[], oneofs=[], - serialized_start=4136, - serialized_end=4388, + serialized_start=4131, + serialized_end=4383, ) _LISTASSETSRESPONSE = _descriptor.Descriptor( @@ -1798,8 +1798,8 @@ syntax="proto3", extension_ranges=[], oneofs=[], - serialized_start=3916, - serialized_end=4388, + serialized_start=3911, + serialized_end=4383, ) @@ -1921,7 +1921,7 @@ containing_type=None, is_extension=False, extension_scope=None, - serialized_options=b"\340A\001", + serialized_options=None, file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), @@ -1972,8 +1972,8 @@ syntax="proto3", extension_ranges=[], oneofs=[], - serialized_start=4391, - serialized_end=4700, + serialized_start=4386, + serialized_end=4690, ) @@ -2089,8 +2089,8 @@ syntax="proto3", extension_ranges=[], oneofs=[], - serialized_start=5239, - serialized_end=5365, + serialized_start=5234, + serialized_end=5360, ) _LISTFINDINGSRESPONSE_LISTFINDINGSRESULT = _descriptor.Descriptor( @@ -2154,7 +2154,7 @@ containing_type=None, is_extension=False, extension_scope=None, - serialized_options=None, + serialized_options=b"\340A\003", file=DESCRIPTOR, create_key=_descriptor._internal_create_key, ), @@ -2167,8 +2167,8 @@ syntax="proto3", extension_ranges=[], oneofs=[], - serialized_start=4931, - serialized_end=5444, + serialized_start=4921, + serialized_end=5439, ) _LISTFINDINGSRESPONSE = _descriptor.Descriptor( @@ -2264,8 +2264,8 @@ syntax="proto3", extension_ranges=[], oneofs=[], - serialized_start=4703, - serialized_end=5444, + serialized_start=4693, + serialized_end=5439, ) @@ -2343,8 +2343,8 @@ syntax="proto3", extension_ranges=[], oneofs=[], - serialized_start=5447, - serialized_end=5659, + serialized_start=5442, + serialized_end=5654, ) @@ -2384,8 +2384,8 @@ syntax="proto3", extension_ranges=[], oneofs=[], - serialized_start=5661, - serialized_end=5761, + serialized_start=5656, + serialized_end=5756, ) @@ -2444,8 +2444,8 @@ syntax="proto3", extension_ranges=[], oneofs=[], - serialized_start=5764, - serialized_end=5905, + serialized_start=5759, + serialized_end=5900, ) @@ -2504,8 +2504,8 @@ syntax="proto3", extension_ranges=[], oneofs=[], - serialized_start=5908, - serialized_end=6083, + serialized_start=5903, + serialized_end=6078, ) @@ -2564,8 +2564,8 @@ syntax="proto3", extension_ranges=[], oneofs=[], - serialized_start=6086, - serialized_end=6267, + serialized_start=6081, + serialized_end=6262, ) @@ -2624,8 +2624,8 @@ syntax="proto3", extension_ranges=[], oneofs=[], - serialized_start=6270, - serialized_end=6408, + serialized_start=6265, + serialized_end=6403, ) @@ -2703,8 +2703,8 @@ syntax="proto3", extension_ranges=[], oneofs=[], - serialized_start=6411, - serialized_end=6619, + serialized_start=6406, + serialized_end=6614, ) _CREATEFINDINGREQUEST.fields_by_name[ @@ -2930,8 +2930,7 @@ “organizations/[organization_id]/sources/[source_id]”. finding_id: Required. Unique identifier provided by the client within the - parent scope. It must be alphanumeric and less than or equal - to 32 characters and greater than 0 characters in length. + parent scope. finding: Required. The Finding being created. The name and security_marks will be ignored as they are both output only @@ -3554,9 +3553,9 @@ only possible state_change is “UNUSED”, which will be the state_change set for all assets present at read_time. field_mask: - Optional. A field mask to specify the ListAssetsResult fields - to be listed in the response. An empty field mask will list - all fields. + A field mask to specify the ListAssetsResult fields to be + listed in the response. An empty field mask will list all + fields. page_token: The value returned by the last ``ListAssetsResponse``; indicates that this is a continuation of a prior @@ -3703,9 +3702,8 @@ which will be the state_change set for all findings present at read_time. field_mask: - Optional. A field mask to specify the Finding fields to be - listed in the response. An empty field mask will list all - fields. + A field mask to specify the Finding fields to be listed in the + response. An empty field mask will list all fields. page_token: The value returned by the last ``ListFindingsResponse``; indicates that this is a continuation of a prior @@ -3972,9 +3970,8 @@ _LISTNOTIFICATIONCONFIGSREQUEST.fields_by_name["parent"]._options = None _LISTSOURCESREQUEST.fields_by_name["parent"]._options = None _LISTASSETSREQUEST.fields_by_name["parent"]._options = None -_LISTASSETSREQUEST.fields_by_name["field_mask"]._options = None _LISTFINDINGSREQUEST.fields_by_name["parent"]._options = None -_LISTFINDINGSREQUEST.fields_by_name["field_mask"]._options = None +_LISTFINDINGSRESPONSE_LISTFINDINGSRESULT.fields_by_name["resource"]._options = None _SETFINDINGSTATEREQUEST.fields_by_name["name"]._options = None _SETFINDINGSTATEREQUEST.fields_by_name["state"]._options = None _SETFINDINGSTATEREQUEST.fields_by_name["start_time"]._options = None @@ -3994,8 +3991,8 @@ index=0, serialized_options=b"\312A\035securitycenter.googleapis.com\322A.https://www.googleapis.com/auth/cloud-platform", create_key=_descriptor._internal_create_key, - serialized_start=6622, - serialized_end=12132, + serialized_start=6617, + serialized_end=12127, methods=[ _descriptor.MethodDescriptor( name="CreateSource", diff --git a/google/cloud/securitycenter_v1p1beta1/proto/securitycenter_service_pb2_grpc.py b/google/cloud/securitycenter_v1p1beta1/proto/securitycenter_service_pb2_grpc.py index b1c98c2f..59b91c3f 100644 --- a/google/cloud/securitycenter_v1p1beta1/proto/securitycenter_service_pb2_grpc.py +++ b/google/cloud/securitycenter_v1p1beta1/proto/securitycenter_service_pb2_grpc.py @@ -167,8 +167,7 @@ def CreateSource(self, request, context): raise NotImplementedError("Method not implemented!") def CreateFinding(self, request, context): - """ - Creates a finding. The corresponding source must exist for finding + """Creates a finding. The corresponding source must exist for finding creation to succeed. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) @@ -280,8 +279,7 @@ def RunAssetDiscovery(self, request, context): raise NotImplementedError("Method not implemented!") def SetFindingState(self, request, context): - """ - Updates the state of a finding. + """Updates the state of a finding. """ context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details("Method not implemented!") diff --git a/google/cloud/securitycenter_v1p1beta1/proto/source_pb2.py b/google/cloud/securitycenter_v1p1beta1/proto/source_pb2.py index 33ac8a80..e50bfc53 100644 --- a/google/cloud/securitycenter_v1p1beta1/proto/source_pb2.py +++ b/google/cloud/securitycenter_v1p1beta1/proto/source_pb2.py @@ -1,7 +1,7 @@ # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/securitycenter_v1p1beta1/proto/source.proto - +"""Generated protocol buffer code.""" from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection diff --git a/noxfile.py b/noxfile.py index 758afabf..6775f51d 100644 --- a/noxfile.py +++ b/noxfile.py @@ -100,6 +100,10 @@ def system(session): """Run the system test suite.""" system_test_path = os.path.join("tests", "system.py") system_test_folder_path = os.path.join("tests", "system") + + # Check the value of `RUN_SYSTEM_TESTS` env var. It defaults to true. + if os.environ.get("RUN_SYSTEM_TESTS", "true") == "false": + session.skip("RUN_SYSTEM_TESTS is set to false, skipping") # Sanity check: Only run tests if the environment variable is set. if not os.environ.get("GOOGLE_APPLICATION_CREDENTIALS", ""): session.skip("Credentials must be set via environment variable") @@ -160,3 +164,38 @@ def docs(session): os.path.join("docs", ""), os.path.join("docs", "_build", "html", ""), ) + + +@nox.session(python=DEFAULT_PYTHON_VERSION) +def docfx(session): + """Build the docfx yaml files for this library.""" + + session.install("-e", ".") + # sphinx-docfx-yaml supports up to sphinx version 1.5.5. + # https://github.com/docascode/sphinx-docfx-yaml/issues/97 + session.install("sphinx==1.5.5", "alabaster", "recommonmark", "sphinx-docfx-yaml") + + shutil.rmtree(os.path.join("docs", "_build"), ignore_errors=True) + session.run( + "sphinx-build", + "-T", # show full traceback on exception + "-N", # no colors + "-D", + ( + "extensions=sphinx.ext.autodoc," + "sphinx.ext.autosummary," + "docfx_yaml.extension," + "sphinx.ext.intersphinx," + "sphinx.ext.coverage," + "sphinx.ext.napoleon," + "sphinx.ext.todo," + "sphinx.ext.viewcode," + "recommonmark" + ), + "-b", + "html", + "-d", + os.path.join("docs", "_build", "doctrees", ""), + os.path.join("docs", ""), + os.path.join("docs", "_build", "html", ""), + ) diff --git a/scripts/decrypt-secrets.sh b/scripts/decrypt-secrets.sh index ff599eb2..21f6d2a2 100755 --- a/scripts/decrypt-secrets.sh +++ b/scripts/decrypt-secrets.sh @@ -20,14 +20,27 @@ ROOT=$( dirname "$DIR" ) # Work from the project root. cd $ROOT +# Prevent it from overriding files. +# We recommend that sample authors use their own service account files and cloud project. +# In that case, they are supposed to prepare these files by themselves. +if [[ -f "testing/test-env.sh" ]] || \ + [[ -f "testing/service-account.json" ]] || \ + [[ -f "testing/client-secrets.json" ]]; then + echo "One or more target files exist, aborting." + exit 1 +fi + # Use SECRET_MANAGER_PROJECT if set, fallback to cloud-devrel-kokoro-resources. PROJECT_ID="${SECRET_MANAGER_PROJECT:-cloud-devrel-kokoro-resources}" gcloud secrets versions access latest --secret="python-docs-samples-test-env" \ + --project="${PROJECT_ID}" \ > testing/test-env.sh gcloud secrets versions access latest \ --secret="python-docs-samples-service-account" \ + --project="${PROJECT_ID}" \ > testing/service-account.json gcloud secrets versions access latest \ --secret="python-docs-samples-client-secrets" \ - > testing/client-secrets.json \ No newline at end of file + --project="${PROJECT_ID}" \ + > testing/client-secrets.json diff --git a/synth.metadata b/synth.metadata index d785b01e..4f8baed8 100644 --- a/synth.metadata +++ b/synth.metadata @@ -3,30 +3,22 @@ { "git": { "name": ".", - "remote": "https://github.com/googleapis/python-securitycenter.git", - "sha": "c70d7904425ae5ac252ffa7317ec6d08234a6c27" - } - }, - { - "git": { - "name": "googleapis", - "remote": "https://github.com/googleapis/googleapis.git", - "sha": "868615a5c1c1059c636bb3d82a555edb1d5a251e", - "internalRef": "324294521" + "remote": "git@github.com:googleapis/python-securitycenter.git", + "sha": "6dcada9bc75d2d411ece89bd704adbaef1e94cfd" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "799d8e6522c1ef7cb55a70d9ea0b15e045c3d00b" + "sha": "ffcee7952b74f647cbb3ef021d95422f10816fca" } }, { "git": { "name": "synthtool", "remote": "https://github.com/googleapis/synthtool.git", - "sha": "799d8e6522c1ef7cb55a70d9ea0b15e045c3d00b" + "sha": "ffcee7952b74f647cbb3ef021d95422f10816fca" } } ], diff --git a/tests/unit/gapic/v1/test_security_center_client_v1.py b/tests/unit/gapic/v1/test_security_center_client_v1.py index dbecf0c9..96cf1bd2 100644 --- a/tests/unit/gapic/v1/test_security_center_client_v1.py +++ b/tests/unit/gapic/v1/test_security_center_client_v1.py @@ -74,196 +74,6 @@ class CustomException(Exception): class TestSecurityCenterClient(object): - def test_get_iam_policy(self): - # Setup Expected Response - version = 351608024 - etag = b"21" - expected_response = {"version": version, "etag": etag} - expected_response = policy_pb2.Policy(**expected_response) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - resource = "resource-341064690" - - response = client.get_iam_policy(resource) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_get_iam_policy_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - resource = "resource-341064690" - - with pytest.raises(CustomException): - client.get_iam_policy(resource) - - def test_group_assets(self): - # Setup Expected Response - next_page_token = "" - total_size = 705419236 - group_by_results_element = {} - group_by_results = [group_by_results_element] - expected_response = { - "next_page_token": next_page_token, - "total_size": total_size, - "group_by_results": group_by_results, - } - expected_response = securitycenter_service_pb2.GroupAssetsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - parent = client.organization_path("[ORGANIZATION]") - group_by = "groupBy506361367" - - paged_list_response = client.group_assets(parent, group_by) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.group_by_results[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.GroupAssetsRequest( - parent=parent, group_by=group_by - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_group_assets_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - parent = client.organization_path("[ORGANIZATION]") - group_by = "groupBy506361367" - - paged_list_response = client.group_assets(parent, group_by) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_group_findings(self): - # Setup Expected Response - next_page_token = "" - total_size = 705419236 - group_by_results_element = {} - group_by_results = [group_by_results_element] - expected_response = { - "next_page_token": next_page_token, - "total_size": total_size, - "group_by_results": group_by_results, - } - expected_response = securitycenter_service_pb2.GroupFindingsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - parent = client.source_path("[ORGANIZATION]", "[SOURCE]") - group_by = "groupBy506361367" - - paged_list_response = client.group_findings(parent, group_by) - resources = list(paged_list_response) - assert len(resources) == 1 - - assert expected_response.group_by_results[0] == resources[0] - - assert len(channel.requests) == 1 - expected_request = securitycenter_service_pb2.GroupFindingsRequest( - parent=parent, group_by=group_by - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_group_findings_exception(self): - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - parent = client.source_path("[ORGANIZATION]", "[SOURCE]") - group_by = "groupBy506361367" - - paged_list_response = client.group_findings(parent, group_by) - with pytest.raises(CustomException): - list(paged_list_response) - - def test_test_iam_permissions(self): - # Setup Expected Response - expected_response = {} - expected_response = iam_policy_pb2.TestIamPermissionsResponse( - **expected_response - ) - - # Mock the API response - channel = ChannelStub(responses=[expected_response]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup Request - resource = "resource-341064690" - permissions = [] - - response = client.test_iam_permissions(resource, permissions) - assert expected_response == response - - assert len(channel.requests) == 1 - expected_request = iam_policy_pb2.TestIamPermissionsRequest( - resource=resource, permissions=permissions - ) - actual_request = channel.requests[0][1] - assert expected_request == actual_request - - def test_test_iam_permissions_exception(self): - # Mock the API response - channel = ChannelStub(responses=[CustomException()]) - patch = mock.patch("google.api_core.grpc_helpers.create_channel") - with patch as create_channel: - create_channel.return_value = channel - client = securitycenter_v1.SecurityCenterClient() - - # Setup request - resource = "resource-341064690" - permissions = [] - - with pytest.raises(CustomException): - client.test_iam_permissions(resource, permissions) - def test_create_source(self): # Setup Expected Response name = "name3373707" @@ -459,6 +269,45 @@ def test_delete_notification_config_exception(self): with pytest.raises(CustomException): client.delete_notification_config(name) + def test_get_iam_policy(self): + # Setup Expected Response + version = 351608024 + etag = b"21" + expected_response = {"version": version, "etag": etag} + expected_response = policy_pb2.Policy(**expected_response) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + patch = mock.patch("google.api_core.grpc_helpers.create_channel") + with patch as create_channel: + create_channel.return_value = channel + client = securitycenter_v1.SecurityCenterClient() + + # Setup Request + resource = "resource-341064690" + + response = client.get_iam_policy(resource) + assert expected_response == response + + assert len(channel.requests) == 1 + expected_request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_get_iam_policy_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + patch = mock.patch("google.api_core.grpc_helpers.create_channel") + with patch as create_channel: + create_channel.return_value = channel + client = securitycenter_v1.SecurityCenterClient() + + # Setup request + resource = "resource-341064690" + + with pytest.raises(CustomException): + client.get_iam_policy(resource) + def test_get_notification_config(self): # Setup Expected Response name_2 = "name2-1052831874" @@ -603,6 +452,114 @@ def test_get_source_exception(self): with pytest.raises(CustomException): client.get_source(name) + def test_group_assets(self): + # Setup Expected Response + next_page_token = "" + total_size = 705419236 + group_by_results_element = {} + group_by_results = [group_by_results_element] + expected_response = { + "next_page_token": next_page_token, + "total_size": total_size, + "group_by_results": group_by_results, + } + expected_response = securitycenter_service_pb2.GroupAssetsResponse( + **expected_response + ) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + patch = mock.patch("google.api_core.grpc_helpers.create_channel") + with patch as create_channel: + create_channel.return_value = channel + client = securitycenter_v1.SecurityCenterClient() + + # Setup Request + parent = client.organization_path("[ORGANIZATION]") + group_by = "groupBy506361367" + + paged_list_response = client.group_assets(parent, group_by) + resources = list(paged_list_response) + assert len(resources) == 1 + + assert expected_response.group_by_results[0] == resources[0] + + assert len(channel.requests) == 1 + expected_request = securitycenter_service_pb2.GroupAssetsRequest( + parent=parent, group_by=group_by + ) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_group_assets_exception(self): + channel = ChannelStub(responses=[CustomException()]) + patch = mock.patch("google.api_core.grpc_helpers.create_channel") + with patch as create_channel: + create_channel.return_value = channel + client = securitycenter_v1.SecurityCenterClient() + + # Setup request + parent = client.organization_path("[ORGANIZATION]") + group_by = "groupBy506361367" + + paged_list_response = client.group_assets(parent, group_by) + with pytest.raises(CustomException): + list(paged_list_response) + + def test_group_findings(self): + # Setup Expected Response + next_page_token = "" + total_size = 705419236 + group_by_results_element = {} + group_by_results = [group_by_results_element] + expected_response = { + "next_page_token": next_page_token, + "total_size": total_size, + "group_by_results": group_by_results, + } + expected_response = securitycenter_service_pb2.GroupFindingsResponse( + **expected_response + ) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + patch = mock.patch("google.api_core.grpc_helpers.create_channel") + with patch as create_channel: + create_channel.return_value = channel + client = securitycenter_v1.SecurityCenterClient() + + # Setup Request + parent = client.source_path("[ORGANIZATION]", "[SOURCE]") + group_by = "groupBy506361367" + + paged_list_response = client.group_findings(parent, group_by) + resources = list(paged_list_response) + assert len(resources) == 1 + + assert expected_response.group_by_results[0] == resources[0] + + assert len(channel.requests) == 1 + expected_request = securitycenter_service_pb2.GroupFindingsRequest( + parent=parent, group_by=group_by + ) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_group_findings_exception(self): + channel = ChannelStub(responses=[CustomException()]) + patch = mock.patch("google.api_core.grpc_helpers.create_channel") + with patch as create_channel: + create_channel.return_value = channel + client = securitycenter_v1.SecurityCenterClient() + + # Setup request + parent = client.source_path("[ORGANIZATION]", "[SOURCE]") + group_by = "groupBy506361367" + + paged_list_response = client.group_findings(parent, group_by) + with pytest.raises(CustomException): + list(paged_list_response) + def test_list_assets(self): # Setup Expected Response next_page_token = "" @@ -949,6 +906,49 @@ def test_set_iam_policy_exception(self): with pytest.raises(CustomException): client.set_iam_policy(resource, policy) + def test_test_iam_permissions(self): + # Setup Expected Response + expected_response = {} + expected_response = iam_policy_pb2.TestIamPermissionsResponse( + **expected_response + ) + + # Mock the API response + channel = ChannelStub(responses=[expected_response]) + patch = mock.patch("google.api_core.grpc_helpers.create_channel") + with patch as create_channel: + create_channel.return_value = channel + client = securitycenter_v1.SecurityCenterClient() + + # Setup Request + resource = "resource-341064690" + permissions = [] + + response = client.test_iam_permissions(resource, permissions) + assert expected_response == response + + assert len(channel.requests) == 1 + expected_request = iam_policy_pb2.TestIamPermissionsRequest( + resource=resource, permissions=permissions + ) + actual_request = channel.requests[0][1] + assert expected_request == actual_request + + def test_test_iam_permissions_exception(self): + # Mock the API response + channel = ChannelStub(responses=[CustomException()]) + patch = mock.patch("google.api_core.grpc_helpers.create_channel") + with patch as create_channel: + create_channel.return_value = channel + client = securitycenter_v1.SecurityCenterClient() + + # Setup request + resource = "resource-341064690" + permissions = [] + + with pytest.raises(CustomException): + client.test_iam_permissions(resource, permissions) + def test_update_finding(self): # Setup Expected Response name = "name3373707" diff --git a/tests/unit/gapic/v1beta1/test_security_center_client_v1beta1.py b/tests/unit/gapic/v1beta1/test_security_center_client_v1beta1.py index bab98fc9..3cc4f388 100644 --- a/tests/unit/gapic/v1beta1/test_security_center_client_v1beta1.py +++ b/tests/unit/gapic/v1beta1/test_security_center_client_v1beta1.py @@ -189,7 +189,7 @@ def test_get_iam_policy(self): client = securitycenter_v1beta1.SecurityCenterClient() # Setup Request - resource = client.source_path("[ORGANIZATION]", "[SOURCE]") + resource = "resource-341064690" response = client.get_iam_policy(resource) assert expected_response == response @@ -208,7 +208,7 @@ def test_get_iam_policy_exception(self): client = securitycenter_v1beta1.SecurityCenterClient() # Setup request - resource = client.source_path("[ORGANIZATION]", "[SOURCE]") + resource = "resource-341064690" with pytest.raises(CustomException): client.get_iam_policy(resource) @@ -673,7 +673,7 @@ def test_set_iam_policy(self): client = securitycenter_v1beta1.SecurityCenterClient() # Setup Request - resource = client.source_path("[ORGANIZATION]", "[SOURCE]") + resource = "resource-341064690" policy = {} response = client.set_iam_policy(resource, policy) @@ -695,7 +695,7 @@ def test_set_iam_policy_exception(self): client = securitycenter_v1beta1.SecurityCenterClient() # Setup request - resource = client.source_path("[ORGANIZATION]", "[SOURCE]") + resource = "resource-341064690" policy = {} with pytest.raises(CustomException): @@ -716,7 +716,7 @@ def test_test_iam_permissions(self): client = securitycenter_v1beta1.SecurityCenterClient() # Setup Request - resource = client.source_path("[ORGANIZATION]", "[SOURCE]") + resource = "resource-341064690" permissions = [] response = client.test_iam_permissions(resource, permissions) @@ -738,7 +738,7 @@ def test_test_iam_permissions_exception(self): client = securitycenter_v1beta1.SecurityCenterClient() # Setup request - resource = client.source_path("[ORGANIZATION]", "[SOURCE]") + resource = "resource-341064690" permissions = [] with pytest.raises(CustomException): From 9be73f20ec4380921c10a10f165bab14ea948dd4 Mon Sep 17 00:00:00 2001 From: Bu Sun Kim Date: Thu, 10 Sep 2020 16:35:45 +0000 Subject: [PATCH 15/17] remove microgen surface --- google/__init__.py | 24 - google/cloud/__init__.py | 24 - google/cloud/securitycenter_v1/py.typed | 2 - .../securitycenter_v1/services/__init__.py | 16 - .../services/security_center/__init__.py | 24 - .../services/security_center/async_client.py | 2226 --------------- .../services/security_center/client.py | 2380 ---------------- .../services/security_center/pagers.py | 804 ------ .../security_center/transports/__init__.py | 36 - .../security_center/transports/base.py | 566 ---- .../security_center/transports/grpc.py | 900 ------ .../transports/grpc_asyncio.py | 905 ------ .../cloud/securitycenter_v1/types/__init__.py | 95 - google/cloud/securitycenter_v1/types/asset.py | 166 -- .../cloud/securitycenter_v1/types/finding.py | 123 - .../types/notification_config.py | 100 - .../types/notification_message.py | 54 - .../types/organization_settings.py | 89 - .../cloud/securitycenter_v1/types/resource.py | 56 - .../types/run_asset_discovery_response.py | 52 - .../securitycenter_v1/types/security_marks.py | 57 - .../types/securitycenter_service.py | 1353 --------- .../cloud/securitycenter_v1/types/source.py | 64 - google/cloud/securitycenter_v1beta1/py.typed | 2 - .../services/__init__.py | 16 - .../services/security_center/__init__.py | 24 - .../services/security_center/async_client.py | 1801 ------------ .../services/security_center/client.py | 1933 ------------- .../services/security_center/pagers.py | 668 ----- .../security_center/transports/__init__.py | 36 - .../security_center/transports/base.py | 465 ---- .../security_center/transports/grpc.py | 754 ----- .../transports/grpc_asyncio.py | 759 ----- .../securitycenter_v1beta1/types/__init__.py | 77 - .../securitycenter_v1beta1/types/asset.py | 129 - .../securitycenter_v1beta1/types/finding.py | 125 - .../types/organization_settings.py | 89 - .../types/run_asset_discovery_response.py | 53 - .../types/security_marks.py | 57 - .../types/securitycenter_service.py | 862 ------ .../securitycenter_v1beta1/types/source.py | 64 - .../cloud/securitycenter_v1p1beta1/py.typed | 2 - .../services/__init__.py | 16 - .../services/security_center/__init__.py | 24 - .../services/security_center/async_client.py | 2317 --------------- .../services/security_center/client.py | 2473 ----------------- .../services/security_center/pagers.py | 804 ------ .../security_center/transports/__init__.py | 36 - .../security_center/transports/base.py | 568 ---- .../security_center/transports/grpc.py | 904 ------ .../transports/grpc_asyncio.py | 909 ------ .../types/__init__.py | 95 - .../securitycenter_v1p1beta1/types/asset.py | 168 -- .../securitycenter_v1p1beta1/types/finding.py | 125 - .../types/notification_config.py | 109 - .../types/notification_message.py | 53 - .../types/organization_settings.py | 89 - .../types/resource.py | 56 - .../types/run_asset_discovery_response.py | 53 - .../types/security_marks.py | 57 - .../types/securitycenter_service.py | 1356 --------- .../securitycenter_v1p1beta1/types/source.py | 64 - synth.metadata | 2 +- 63 files changed, 1 insertion(+), 28309 deletions(-) delete mode 100644 google/__init__.py delete mode 100644 google/cloud/__init__.py delete mode 100644 google/cloud/securitycenter_v1/py.typed delete mode 100644 google/cloud/securitycenter_v1/services/__init__.py delete mode 100644 google/cloud/securitycenter_v1/services/security_center/__init__.py delete mode 100644 google/cloud/securitycenter_v1/services/security_center/async_client.py delete mode 100644 google/cloud/securitycenter_v1/services/security_center/client.py delete mode 100644 google/cloud/securitycenter_v1/services/security_center/pagers.py delete mode 100644 google/cloud/securitycenter_v1/services/security_center/transports/__init__.py delete mode 100644 google/cloud/securitycenter_v1/services/security_center/transports/base.py delete mode 100644 google/cloud/securitycenter_v1/services/security_center/transports/grpc.py delete mode 100644 google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py delete mode 100644 google/cloud/securitycenter_v1/types/__init__.py delete mode 100644 google/cloud/securitycenter_v1/types/asset.py delete mode 100644 google/cloud/securitycenter_v1/types/finding.py delete mode 100644 google/cloud/securitycenter_v1/types/notification_config.py delete mode 100644 google/cloud/securitycenter_v1/types/notification_message.py delete mode 100644 google/cloud/securitycenter_v1/types/organization_settings.py delete mode 100644 google/cloud/securitycenter_v1/types/resource.py delete mode 100644 google/cloud/securitycenter_v1/types/run_asset_discovery_response.py delete mode 100644 google/cloud/securitycenter_v1/types/security_marks.py delete mode 100644 google/cloud/securitycenter_v1/types/securitycenter_service.py delete mode 100644 google/cloud/securitycenter_v1/types/source.py delete mode 100644 google/cloud/securitycenter_v1beta1/py.typed delete mode 100644 google/cloud/securitycenter_v1beta1/services/__init__.py delete mode 100644 google/cloud/securitycenter_v1beta1/services/security_center/__init__.py delete mode 100644 google/cloud/securitycenter_v1beta1/services/security_center/async_client.py delete mode 100644 google/cloud/securitycenter_v1beta1/services/security_center/client.py delete mode 100644 google/cloud/securitycenter_v1beta1/services/security_center/pagers.py delete mode 100644 google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py delete mode 100644 google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py delete mode 100644 google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py delete mode 100644 google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py delete mode 100644 google/cloud/securitycenter_v1beta1/types/__init__.py delete mode 100644 google/cloud/securitycenter_v1beta1/types/asset.py delete mode 100644 google/cloud/securitycenter_v1beta1/types/finding.py delete mode 100644 google/cloud/securitycenter_v1beta1/types/organization_settings.py delete mode 100644 google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py delete mode 100644 google/cloud/securitycenter_v1beta1/types/security_marks.py delete mode 100644 google/cloud/securitycenter_v1beta1/types/securitycenter_service.py delete mode 100644 google/cloud/securitycenter_v1beta1/types/source.py delete mode 100644 google/cloud/securitycenter_v1p1beta1/py.typed delete mode 100644 google/cloud/securitycenter_v1p1beta1/services/__init__.py delete mode 100644 google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py delete mode 100644 google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py delete mode 100644 google/cloud/securitycenter_v1p1beta1/services/security_center/client.py delete mode 100644 google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py delete mode 100644 google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py delete mode 100644 google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py delete mode 100644 google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py delete mode 100644 google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py delete mode 100644 google/cloud/securitycenter_v1p1beta1/types/__init__.py delete mode 100644 google/cloud/securitycenter_v1p1beta1/types/asset.py delete mode 100644 google/cloud/securitycenter_v1p1beta1/types/finding.py delete mode 100644 google/cloud/securitycenter_v1p1beta1/types/notification_config.py delete mode 100644 google/cloud/securitycenter_v1p1beta1/types/notification_message.py delete mode 100644 google/cloud/securitycenter_v1p1beta1/types/organization_settings.py delete mode 100644 google/cloud/securitycenter_v1p1beta1/types/resource.py delete mode 100644 google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py delete mode 100644 google/cloud/securitycenter_v1p1beta1/types/security_marks.py delete mode 100644 google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py delete mode 100644 google/cloud/securitycenter_v1p1beta1/types/source.py diff --git a/google/__init__.py b/google/__init__.py deleted file mode 100644 index 8fcc60e2..00000000 --- a/google/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2019 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. - -try: - import pkg_resources - - pkg_resources.declare_namespace(__name__) -except ImportError: - import pkgutil - - __path__ = pkgutil.extend_path(__path__, __name__) diff --git a/google/cloud/__init__.py b/google/cloud/__init__.py deleted file mode 100644 index 8fcc60e2..00000000 --- a/google/cloud/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# -*- coding: utf-8 -*- -# -# Copyright 2019 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. - -try: - import pkg_resources - - pkg_resources.declare_namespace(__name__) -except ImportError: - import pkgutil - - __path__ = pkgutil.extend_path(__path__, __name__) diff --git a/google/cloud/securitycenter_v1/py.typed b/google/cloud/securitycenter_v1/py.typed deleted file mode 100644 index 23a44fc7..00000000 --- a/google/cloud/securitycenter_v1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-securitycenter package uses inline types. diff --git a/google/cloud/securitycenter_v1/services/__init__.py b/google/cloud/securitycenter_v1/services/__init__.py deleted file mode 100644 index 42ffdf2b..00000000 --- a/google/cloud/securitycenter_v1/services/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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. -# diff --git a/google/cloud/securitycenter_v1/services/security_center/__init__.py b/google/cloud/securitycenter_v1/services/security_center/__init__.py deleted file mode 100644 index 6250349b..00000000 --- a/google/cloud/securitycenter_v1/services/security_center/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 SecurityCenterClient -from .async_client import SecurityCenterAsyncClient - -__all__ = ( - "SecurityCenterClient", - "SecurityCenterAsyncClient", -) diff --git a/google/cloud/securitycenter_v1/services/security_center/async_client.py b/google/cloud/securitycenter_v1/services/security_center/async_client.py deleted file mode 100644 index 147b43bd..00000000 --- a/google/cloud/securitycenter_v1/services/security_center/async_client.py +++ /dev/null @@ -1,2226 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation -from google.api_core import operation_async -from google.cloud.securitycenter_v1.services.security_center import pagers -from google.cloud.securitycenter_v1.types import finding -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import ( - notification_config as gcs_notification_config, -) -from google.cloud.securitycenter_v1.types import organization_settings -from google.cloud.securitycenter_v1.types import ( - organization_settings as gcs_organization_settings, -) -from google.cloud.securitycenter_v1.types import run_asset_discovery_response -from google.cloud.securitycenter_v1.types import security_marks -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import source -from google.cloud.securitycenter_v1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - -from .transports.base import SecurityCenterTransport -from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .client import SecurityCenterClient - - -class SecurityCenterAsyncClient: - """V1 APIs for Security Center service.""" - - _client: SecurityCenterClient - - DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - - security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) - - finding_path = staticmethod(SecurityCenterClient.finding_path) - - notification_config_path = staticmethod( - SecurityCenterClient.notification_config_path - ) - - source_path = staticmethod(SecurityCenterClient.source_path) - - organization_settings_path = staticmethod( - SecurityCenterClient.organization_settings_path - ) - - from_service_account_file = SecurityCenterClient.from_service_account_file - from_service_account_json = from_service_account_file - - get_transport_class = functools.partial( - type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient) - ) - - def __init__( - self, - *, - credentials: credentials.Credentials = None, - transport: Union[str, SecurityCenterTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - ) -> None: - """Instantiate the security center 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. - transport (Union[str, ~.SecurityCenterTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint, this is the default value for - the environment variable) and "auto" (auto switch to the default - mTLS endpoint if client SSL credentials is present). However, - the ``api_endpoint`` property takes precedence if provided. - (2) The ``client_cert_source`` property is used to provide client - SSL credentials for mutual TLS transport. If not provided, the - default SSL credentials will be used if present. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - - self._client = SecurityCenterClient( - credentials=credentials, transport=transport, client_options=client_options, - ) - - async def create_source( - self, - request: securitycenter_service.CreateSourceRequest = None, - *, - parent: str = None, - source: gcs_source.Source = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Creates a source. - - Args: - request (:class:`~.securitycenter_service.CreateSourceRequest`): - The request object. Request message for creating a - source. - parent (:class:`str`): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (:class:`~.gcs_source.Source`): - Required. The Source being created, only the - display_name and description will be used. All other - fields will be ignored. - This corresponds to the ``source`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([parent, source]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.CreateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_source, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def create_finding( - self, - request: securitycenter_service.CreateFindingRequest = None, - *, - parent: str = None, - finding_id: str = None, - finding: gcs_finding.Finding = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Args: - request (:class:`~.securitycenter_service.CreateFindingRequest`): - The request object. Request message for creating a - finding. - parent (:class:`str`): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding_id (:class:`str`): - Required. Unique identifier provided - by the client within the parent scope. - It must be alphanumeric and less than or - equal to 32 characters and greater than - 0 characters in length. - This corresponds to the ``finding_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding (:class:`~.gcs_finding.Finding`): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output - only fields on this resource. - This corresponds to the ``finding`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_finding.Finding: - Security Command Center finding. - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([parent, finding_id, finding]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.CreateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if finding_id is not None: - request.finding_id = finding_id - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_finding, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def create_notification_config( - self, - request: securitycenter_service.CreateNotificationConfigRequest = None, - *, - parent: str = None, - config_id: str = None, - notification_config: gcs_notification_config.NotificationConfig = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Creates a notification config. - - Args: - request (:class:`~.securitycenter_service.CreateNotificationConfigRequest`): - The request object. Request message for creating a - notification config. - parent (:class:`str`): - Required. Resource name of the new notification config's - parent. Its format is "organizations/[organization_id]". - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - config_id (:class:`str`): - Required. - Unique identifier provided by the client - within the parent scope. It must be - between 1 and 128 characters, and - contains alphanumeric characters, - underscores or hyphens only. - This corresponds to the ``config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - notification_config (:class:`~.gcs_notification_config.NotificationConfig`): - Required. The notification config - being created. The name and the service - account will be ignored as they are both - output only fields on this resource. - This corresponds to the ``notification_config`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_notification_config.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([parent, config_id, notification_config]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.CreateNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if config_id is not None: - request.config_id = config_id - if notification_config is not None: - request.notification_config = notification_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_notification_config, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def delete_notification_config( - self, - request: securitycenter_service.DeleteNotificationConfigRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a notification config. - - Args: - request (:class:`~.securitycenter_service.DeleteNotificationConfigRequest`): - The request object. Request message for deleting a - notification config. - name (:class:`str`): - Required. Name of the notification config to delete. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_id]". - This corresponds to the ``name`` 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([name]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.DeleteNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_notification_config, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - await rpc( - request, retry=retry, timeout=timeout, metadata=metadata, - ) - - async def get_iam_policy( - self, - request: iam_policy.GetIamPolicyRequest = None, - *, - resource: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: - r"""Gets the access control policy on the specified - Source. - - Args: - request (:class:`~.iam_policy.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - This corresponds to the ``resource`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([resource]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.GetIamPolicyRequest(**request) - - elif not request: - request = iam_policy.GetIamPolicyRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_iam_policy, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_notification_config( - self, - request: securitycenter_service.GetNotificationConfigRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> notification_config.NotificationConfig: - r"""Gets a notification config. - - Args: - request (:class:`~.securitycenter_service.GetNotificationConfigRequest`): - The request object. Request message for getting a - notification config. - name (:class:`str`): - Required. Name of the notification config to get. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_id]". - This corresponds to the ``name`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.notification_config.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([name]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.GetNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_notification_config, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_organization_settings( - self, - request: securitycenter_service.GetOrganizationSettingsRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> organization_settings.OrganizationSettings: - r"""Gets the settings for an organization. - - Args: - request (:class:`~.securitycenter_service.GetOrganizationSettingsRequest`): - The request object. Request message for getting - organization settings. - name (:class:`str`): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - This corresponds to the ``name`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.organization_settings.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([name]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.GetOrganizationSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_organization_settings, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_source( - self, - request: securitycenter_service.GetSourceRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> source.Source: - r"""Gets a source. - - Args: - request (:class:`~.securitycenter_service.GetSourceRequest`): - The request object. Request message for getting a - source. - name (:class:`str`): - Required. Relative resource name of the source. Its - format is - "organizations/[organization_id]/source/[source_id]". - This corresponds to the ``name`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([name]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.GetSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_source, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def group_assets( - self, - request: securitycenter_service.GroupAssetsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupAssetsAsyncPager: - r"""Filters an organization's assets and groups them by - their specified properties. - - Args: - request (:class:`~.securitycenter_service.GroupAssetsRequest`): - The request object. Request message for grouping by - assets. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.GroupAssetsAsyncPager: - Response message for grouping by - assets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - - request = securitycenter_service.GroupAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.group_assets, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.GroupAssetsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - async def group_findings( - self, - request: securitycenter_service.GroupFindingsRequest = None, - *, - parent: str = None, - group_by: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupFindingsAsyncPager: - r"""Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings - - Args: - request (:class:`~.securitycenter_service.GroupFindingsRequest`): - The request object. Request message for grouping by - findings. - parent (:class:`str`): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]". - To groupBy across all sources provide a source_id of - ``-``. For example: - organizations/{organization_id}/sources/- - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - group_by (:class:`str`): - Required. Expression that defines what assets fields to - use for grouping (including ``state_change``). The - string value should follow SQL syntax: comma separated - list of fields. For example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - - The following fields are supported when compare_duration - is set: - - - state_change - This corresponds to the ``group_by`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.GroupFindingsAsyncPager: - Response message for group by - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([parent, group_by]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.GroupFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.group_findings, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.GroupFindingsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_assets( - self, - request: securitycenter_service.ListAssetsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAssetsAsyncPager: - r"""Lists an organization's assets. - - Args: - request (:class:`~.securitycenter_service.ListAssetsRequest`): - The request object. Request message for listing assets. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.ListAssetsAsyncPager: - Response message for listing assets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - - request = securitycenter_service.ListAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_assets, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListAssetsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_findings( - self, - request: securitycenter_service.ListFindingsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFindingsAsyncPager: - r"""Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings - - Args: - request (:class:`~.securitycenter_service.ListFindingsRequest`): - The request object. Request message for listing - findings. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.ListFindingsAsyncPager: - Response message for listing - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - - request = securitycenter_service.ListFindingsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_findings, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListFindingsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_notification_configs( - self, - request: securitycenter_service.ListNotificationConfigsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListNotificationConfigsAsyncPager: - r"""Lists notification configs. - - Args: - request (:class:`~.securitycenter_service.ListNotificationConfigsRequest`): - The request object. Request message for listing - notification configs. - parent (:class:`str`): - Required. Name of the organization to list notification - configs. Its format is - "organizations/[organization_id]". - This corresponds to the ``parent`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.ListNotificationConfigsAsyncPager: - Response message for listing - notification configs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.ListNotificationConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_notification_configs, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListNotificationConfigsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_sources( - self, - request: securitycenter_service.ListSourcesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSourcesAsyncPager: - r"""Lists all sources belonging to an organization. - - Args: - request (:class:`~.securitycenter_service.ListSourcesRequest`): - The request object. Request message for listing sources. - parent (:class:`str`): - Required. Resource name of the parent of sources to - list. Its format should be - "organizations/[organization_id]". - This corresponds to the ``parent`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.ListSourcesAsyncPager: - Response message for listing sources. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.ListSourcesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_sources, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListSourcesAsyncPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - async def run_asset_discovery( - self, - request: securitycenter_service.RunAssetDiscoveryRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Args: - request (:class:`~.securitycenter_service.RunAssetDiscoveryRequest`): - The request object. Request message for running asset - discovery for an organization. - parent (:class:`str`): - Required. Name of the organization to run asset - discovery for. Its format is - "organizations/[organization_id]". - This corresponds to the ``parent`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:``~.run_asset_discovery_response.RunAssetDiscoveryResponse``: - Response of asset discovery run - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.RunAssetDiscoveryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.run_asset_discovery, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - run_asset_discovery_response.RunAssetDiscoveryResponse, - metadata_type=empty.Empty, - ) - - # Done; return the response. - return response - - async def set_finding_state( - self, - request: securitycenter_service.SetFindingStateRequest = None, - *, - name: str = None, - state: finding.Finding.State = None, - start_time: timestamp.Timestamp = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the state of a finding. - - Args: - request (:class:`~.securitycenter_service.SetFindingStateRequest`): - The request object. Request message for updating a - finding's state. - name (:class:`str`): - Required. The relative resource name of the finding. - See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - state (:class:`~.finding.Finding.State`): - Required. The desired State of the - finding. - This corresponds to the ``state`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - start_time (:class:`~.timestamp.Timestamp`): - Required. The time at which the - updated state takes effect. - This corresponds to the ``start_time`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.finding.Finding: - Security Command Center finding. - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([name, state, start_time]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.SetFindingStateRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - if state is not None: - request.state = state - if start_time is not None: - request.start_time = start_time - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_finding_state, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def set_iam_policy( - self, - request: iam_policy.SetIamPolicyRequest = None, - *, - resource: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: - r"""Sets the access control policy on the specified - Source. - - Args: - request (:class:`~.iam_policy.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - This corresponds to the ``resource`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([resource]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.SetIamPolicyRequest(**request) - - elif not request: - request = iam_policy.SetIamPolicyRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def test_iam_permissions( - self, - request: iam_policy.TestIamPermissionsRequest = None, - *, - resource: str = None, - permissions: Sequence[str] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: - r"""Returns the permissions that a caller has on the - specified source. - - Args: - request (:class:`~.iam_policy.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (:class:`Sequence[str]`): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - This corresponds to the ``permissions`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.iam_policy.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([resource, permissions]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.TestIamPermissionsRequest(**request) - - elif not request: - request = iam_policy.TestIamPermissionsRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource - - if permissions: - request.permissions.extend(permissions) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.test_iam_permissions, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def update_finding( - self, - request: securitycenter_service.UpdateFindingRequest = None, - *, - finding: gcs_finding.Finding = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Args: - request (:class:`~.securitycenter_service.UpdateFindingRequest`): - The request object. Request message for updating or - creating a finding. - finding (:class:`~.gcs_finding.Finding`): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the - name must be alphanumeric and less than or equal to 32 - characters and greater than 0 characters in length. - This corresponds to the ``finding`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_finding.Finding: - Security Command Center finding. - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([finding]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.UpdateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_finding, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("finding.name", request.finding.name),) - ), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def update_notification_config( - self, - request: securitycenter_service.UpdateNotificationConfigRequest = None, - *, - notification_config: gcs_notification_config.NotificationConfig = None, - update_mask: field_mask.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Args: - request (:class:`~.securitycenter_service.UpdateNotificationConfigRequest`): - The request object. Request message for updating a - notification config. - notification_config (:class:`~.gcs_notification_config.NotificationConfig`): - Required. The notification config to - update. - This corresponds to the ``notification_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`~.field_mask.FieldMask`): - The FieldMask to use when updating - the notification config. - If empty all mutable fields will be - updated. - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_notification_config.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([notification_config, update_mask]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.UpdateNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if notification_config is not None: - request.notification_config = notification_config - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.update_notification_config, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("notification_config.name", request.notification_config.name),) - ), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def update_organization_settings( - self, - request: securitycenter_service.UpdateOrganizationSettingsRequest = None, - *, - organization_settings: gcs_organization_settings.OrganizationSettings = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Updates an organization's settings. - - Args: - request (:class:`~.securitycenter_service.UpdateOrganizationSettingsRequest`): - The request object. Request message for updating an - organization's settings. - organization_settings (:class:`~.gcs_organization_settings.OrganizationSettings`): - Required. The organization settings - resource to update. - This corresponds to the ``organization_settings`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_organization_settings.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([organization_settings]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.UpdateOrganizationSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if organization_settings is not None: - request.organization_settings = organization_settings - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_organization_settings, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("organization_settings.name", request.organization_settings.name),) - ), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def update_source( - self, - request: securitycenter_service.UpdateSourceRequest = None, - *, - source: gcs_source.Source = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Updates a source. - - Args: - request (:class:`~.securitycenter_service.UpdateSourceRequest`): - The request object. Request message for updating a - source. - source (:class:`~.gcs_source.Source`): - Required. The source resource to - update. - This corresponds to the ``source`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([source]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.UpdateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_source, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("source.name", request.source.name),) - ), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def update_security_marks( - self, - request: securitycenter_service.UpdateSecurityMarksRequest = None, - *, - security_marks: gcs_security_marks.SecurityMarks = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_security_marks.SecurityMarks: - r"""Updates security marks. - - Args: - request (:class:`~.securitycenter_service.UpdateSecurityMarksRequest`): - The request object. Request message for updating a - SecurityMarks resource. - security_marks (:class:`~.gcs_security_marks.SecurityMarks`): - Required. The security marks resource - to update. - This corresponds to the ``security_marks`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_security_marks.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([security_marks]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.UpdateSecurityMarksRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if security_marks is not None: - request.security_marks = security_marks - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_security_marks, - default_timeout=480.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("security_marks.name", request.security_marks.name),) - ), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -try: - _client_info = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-securitycenter", - ).version, - ) -except pkg_resources.DistributionNotFound: - _client_info = gapic_v1.client_info.ClientInfo() - - -__all__ = ("SecurityCenterAsyncClient",) diff --git a/google/cloud/securitycenter_v1/services/security_center/client.py b/google/cloud/securitycenter_v1/services/security_center/client.py deleted file mode 100644 index d88ae32e..00000000 --- a/google/cloud/securitycenter_v1/services/security_center/client.py +++ /dev/null @@ -1,2380 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 -import os -import re -from typing import Callable, Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation -from google.api_core import operation_async -from google.cloud.securitycenter_v1.services.security_center import pagers -from google.cloud.securitycenter_v1.types import finding -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import ( - notification_config as gcs_notification_config, -) -from google.cloud.securitycenter_v1.types import organization_settings -from google.cloud.securitycenter_v1.types import ( - organization_settings as gcs_organization_settings, -) -from google.cloud.securitycenter_v1.types import run_asset_discovery_response -from google.cloud.securitycenter_v1.types import security_marks -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import source -from google.cloud.securitycenter_v1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - -from .transports.base import SecurityCenterTransport -from .transports.grpc import SecurityCenterGrpcTransport -from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport - - -class SecurityCenterClientMeta(type): - """Metaclass for the SecurityCenter 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[SecurityCenterTransport]] - _transport_registry["grpc"] = SecurityCenterGrpcTransport - _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport - - def get_transport_class(cls, label: str = None,) -> Type[SecurityCenterTransport]: - """Return 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 SecurityCenterClient(metaclass=SecurityCenterClientMeta): - """V1 APIs for Security Center service.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Convert 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") - - DEFAULT_ENDPOINT = "securitycenter.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @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: - {@api.name}: 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 - - @staticmethod - def finding_path(organization: str, source: str, finding: str,) -> str: - """Return a fully-qualified finding string.""" - return "organizations/{organization}/sources/{source}/findings/{finding}".format( - organization=organization, source=source, finding=finding, - ) - - @staticmethod - def parse_finding_path(path: str) -> Dict[str, str]: - """Parse a finding path into its component segments.""" - m = re.match( - r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", - path, - ) - return m.groupdict() if m else {} - - @staticmethod - def notification_config_path(organization: str, notification_config: str,) -> str: - """Return a fully-qualified notification_config string.""" - return "organizations/{organization}/notificationConfigs/{notification_config}".format( - organization=organization, notification_config=notification_config, - ) - - @staticmethod - def parse_notification_config_path(path: str) -> Dict[str, str]: - """Parse a notification_config path into its component segments.""" - m = re.match( - r"^organizations/(?P.+?)/notificationConfigs/(?P.+?)$", - path, - ) - return m.groupdict() if m else {} - - @staticmethod - def organization_settings_path(organization: str,) -> str: - """Return a fully-qualified organization_settings string.""" - return "organizations/{organization}/organizationSettings".format( - organization=organization, - ) - - @staticmethod - def parse_organization_settings_path(path: str) -> Dict[str, str]: - """Parse a organization_settings path into its component segments.""" - m = re.match( - r"^organizations/(?P.+?)/organizationSettings$", path - ) - return m.groupdict() if m else {} - - @staticmethod - def security_marks_path(organization: str, asset: str,) -> str: - """Return a fully-qualified security_marks string.""" - return "organizations/{organization}/assets/{asset}/securityMarks".format( - organization=organization, asset=asset, - ) - - @staticmethod - def parse_security_marks_path(path: str) -> Dict[str, str]: - """Parse a security_marks path into its component segments.""" - m = re.match( - r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", - path, - ) - return m.groupdict() if m else {} - - @staticmethod - def source_path(organization: str, source: str,) -> str: - """Return a fully-qualified source string.""" - return "organizations/{organization}/sources/{source}".format( - organization=organization, source=source, - ) - - @staticmethod - def parse_source_path(path: str) -> Dict[str, str]: - """Parse a source path into its component segments.""" - m = re.match( - r"^organizations/(?P.+?)/sources/(?P.+?)$", path - ) - return m.groupdict() if m else {} - - def __init__( - self, - *, - credentials: credentials.Credentials = None, - transport: Union[str, SecurityCenterTransport] = None, - client_options: ClientOptions = None, - ) -> None: - """Instantiate the security center 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. - transport (Union[str, ~.SecurityCenterTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint, this is the default value for - the environment variable) and "auto" (auto switch to the default - mTLS endpoint if client SSL credentials is present). However, - the ``api_endpoint`` property takes precedence if provided. - (2) The ``client_cert_source`` property is used to provide client - SSL credentials for mutual TLS transport. If not provided, the - default SSL credentials will be used if present. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = ClientOptions.from_dict(client_options) - if client_options is None: - client_options = ClientOptions.ClientOptions() - - if client_options.api_endpoint is None: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") - if use_mtls_env == "never": - client_options.api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - has_client_cert_source = ( - client_options.client_cert_source is not None - or mtls.has_default_client_cert_source() - ) - client_options.api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT - if has_client_cert_source - else self.DEFAULT_ENDPOINT - ) - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, SecurityCenterTransport): - # transport is a SecurityCenterTransport instance. - if credentials or client_options.credentials_file: - raise ValueError( - "When providing a transport instance, " - "provide its credentials directly." - ) - if client_options.scopes: - raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=client_options.api_endpoint, - scopes=client_options.scopes, - api_mtls_endpoint=client_options.api_endpoint, - client_cert_source=client_options.client_cert_source, - quota_project_id=client_options.quota_project_id, - ) - - def create_source( - self, - request: securitycenter_service.CreateSourceRequest = None, - *, - parent: str = None, - source: gcs_source.Source = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Creates a source. - - Args: - request (:class:`~.securitycenter_service.CreateSourceRequest`): - The request object. Request message for creating a - source. - parent (:class:`str`): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (:class:`~.gcs_source.Source`): - Required. The Source being created, only the - display_name and description will be used. All other - fields will be ignored. - This corresponds to the ``source`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, source]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.CreateSourceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.CreateSourceRequest): - request = securitycenter_service.CreateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def create_finding( - self, - request: securitycenter_service.CreateFindingRequest = None, - *, - parent: str = None, - finding_id: str = None, - finding: gcs_finding.Finding = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Args: - request (:class:`~.securitycenter_service.CreateFindingRequest`): - The request object. Request message for creating a - finding. - parent (:class:`str`): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding_id (:class:`str`): - Required. Unique identifier provided - by the client within the parent scope. - It must be alphanumeric and less than or - equal to 32 characters and greater than - 0 characters in length. - This corresponds to the ``finding_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding (:class:`~.gcs_finding.Finding`): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output - only fields on this resource. - This corresponds to the ``finding`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_finding.Finding: - Security Command Center finding. - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, finding_id, finding]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.CreateFindingRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.CreateFindingRequest): - request = securitycenter_service.CreateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if finding_id is not None: - request.finding_id = finding_id - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def create_notification_config( - self, - request: securitycenter_service.CreateNotificationConfigRequest = None, - *, - parent: str = None, - config_id: str = None, - notification_config: gcs_notification_config.NotificationConfig = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Creates a notification config. - - Args: - request (:class:`~.securitycenter_service.CreateNotificationConfigRequest`): - The request object. Request message for creating a - notification config. - parent (:class:`str`): - Required. Resource name of the new notification config's - parent. Its format is "organizations/[organization_id]". - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - config_id (:class:`str`): - Required. - Unique identifier provided by the client - within the parent scope. It must be - between 1 and 128 characters, and - contains alphanumeric characters, - underscores or hyphens only. - This corresponds to the ``config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - notification_config (:class:`~.gcs_notification_config.NotificationConfig`): - Required. The notification config - being created. The name and the service - account will be ignored as they are both - output only fields on this resource. - This corresponds to the ``notification_config`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_notification_config.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, config_id, notification_config]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.CreateNotificationConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance( - request, securitycenter_service.CreateNotificationConfigRequest - ): - request = securitycenter_service.CreateNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if config_id is not None: - request.config_id = config_id - if notification_config is not None: - request.notification_config = notification_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.create_notification_config - ] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def delete_notification_config( - self, - request: securitycenter_service.DeleteNotificationConfigRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a notification config. - - Args: - request (:class:`~.securitycenter_service.DeleteNotificationConfigRequest`): - The request object. Request message for deleting a - notification config. - name (:class:`str`): - Required. Name of the notification config to delete. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_id]". - This corresponds to the ``name`` 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.DeleteNotificationConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance( - request, securitycenter_service.DeleteNotificationConfigRequest - ): - request = securitycenter_service.DeleteNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.delete_notification_config - ] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - rpc( - request, retry=retry, timeout=timeout, metadata=metadata, - ) - - def get_iam_policy( - self, - request: iam_policy.GetIamPolicyRequest = None, - *, - resource: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: - r"""Gets the access control policy on the specified - Source. - - Args: - request (:class:`~.iam_policy.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - This corresponds to the ``resource`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - 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." - ) - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.GetIamPolicyRequest(**request) - - elif not request: - request = iam_policy.GetIamPolicyRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_notification_config( - self, - request: securitycenter_service.GetNotificationConfigRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> notification_config.NotificationConfig: - r"""Gets a notification config. - - Args: - request (:class:`~.securitycenter_service.GetNotificationConfigRequest`): - The request object. Request message for getting a - notification config. - name (:class:`str`): - Required. Name of the notification config to get. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_id]". - This corresponds to the ``name`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.notification_config.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.GetNotificationConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): - request = securitycenter_service.GetNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_notification_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_organization_settings( - self, - request: securitycenter_service.GetOrganizationSettingsRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> organization_settings.OrganizationSettings: - r"""Gets the settings for an organization. - - Args: - request (:class:`~.securitycenter_service.GetOrganizationSettingsRequest`): - The request object. Request message for getting - organization settings. - name (:class:`str`): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - This corresponds to the ``name`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.organization_settings.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.GetOrganizationSettingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance( - request, securitycenter_service.GetOrganizationSettingsRequest - ): - request = securitycenter_service.GetOrganizationSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.get_organization_settings - ] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_source( - self, - request: securitycenter_service.GetSourceRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> source.Source: - r"""Gets a source. - - Args: - request (:class:`~.securitycenter_service.GetSourceRequest`): - The request object. Request message for getting a - source. - name (:class:`str`): - Required. Relative resource name of the source. Its - format is - "organizations/[organization_id]/source/[source_id]". - This corresponds to the ``name`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.GetSourceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.GetSourceRequest): - request = securitycenter_service.GetSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def group_assets( - self, - request: securitycenter_service.GroupAssetsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupAssetsPager: - r"""Filters an organization's assets and groups them by - their specified properties. - - Args: - request (:class:`~.securitycenter_service.GroupAssetsRequest`): - The request object. Request message for grouping by - assets. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.GroupAssetsPager: - Response message for grouping by - assets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.GroupAssetsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.GroupAssetsRequest): - request = securitycenter_service.GroupAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.group_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.GroupAssetsPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - def group_findings( - self, - request: securitycenter_service.GroupFindingsRequest = None, - *, - parent: str = None, - group_by: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupFindingsPager: - r"""Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings - - Args: - request (:class:`~.securitycenter_service.GroupFindingsRequest`): - The request object. Request message for grouping by - findings. - parent (:class:`str`): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]". - To groupBy across all sources provide a source_id of - ``-``. For example: - organizations/{organization_id}/sources/- - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - group_by (:class:`str`): - Required. Expression that defines what assets fields to - use for grouping (including ``state_change``). The - string value should follow SQL syntax: comma separated - list of fields. For example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - - The following fields are supported when compare_duration - is set: - - - state_change - This corresponds to the ``group_by`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.GroupFindingsPager: - Response message for group by - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, group_by]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.GroupFindingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.GroupFindingsRequest): - request = securitycenter_service.GroupFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.group_findings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.GroupFindingsPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - def list_assets( - self, - request: securitycenter_service.ListAssetsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAssetsPager: - r"""Lists an organization's assets. - - Args: - request (:class:`~.securitycenter_service.ListAssetsRequest`): - The request object. Request message for listing assets. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.ListAssetsPager: - Response message for listing assets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.ListAssetsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.ListAssetsRequest): - request = securitycenter_service.ListAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListAssetsPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - def list_findings( - self, - request: securitycenter_service.ListFindingsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFindingsPager: - r"""Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings - - Args: - request (:class:`~.securitycenter_service.ListFindingsRequest`): - The request object. Request message for listing - findings. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.ListFindingsPager: - Response message for listing - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.ListFindingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.ListFindingsRequest): - request = securitycenter_service.ListFindingsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_findings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListFindingsPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - def list_notification_configs( - self, - request: securitycenter_service.ListNotificationConfigsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListNotificationConfigsPager: - r"""Lists notification configs. - - Args: - request (:class:`~.securitycenter_service.ListNotificationConfigsRequest`): - The request object. Request message for listing - notification configs. - parent (:class:`str`): - Required. Name of the organization to list notification - configs. Its format is - "organizations/[organization_id]". - This corresponds to the ``parent`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.ListNotificationConfigsPager: - Response message for listing - notification configs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.ListNotificationConfigsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance( - request, securitycenter_service.ListNotificationConfigsRequest - ): - request = securitycenter_service.ListNotificationConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.list_notification_configs - ] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListNotificationConfigsPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - def list_sources( - self, - request: securitycenter_service.ListSourcesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSourcesPager: - r"""Lists all sources belonging to an organization. - - Args: - request (:class:`~.securitycenter_service.ListSourcesRequest`): - The request object. Request message for listing sources. - parent (:class:`str`): - Required. Resource name of the parent of sources to - list. Its format should be - "organizations/[organization_id]". - This corresponds to the ``parent`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.ListSourcesPager: - Response message for listing sources. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.ListSourcesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.ListSourcesRequest): - request = securitycenter_service.ListSourcesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_sources] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListSourcesPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - def run_asset_discovery( - self, - request: securitycenter_service.RunAssetDiscoveryRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Args: - request (:class:`~.securitycenter_service.RunAssetDiscoveryRequest`): - The request object. Request message for running asset - discovery for an organization. - parent (:class:`str`): - Required. Name of the organization to run asset - discovery for. Its format is - "organizations/[organization_id]". - This corresponds to the ``parent`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:``~.run_asset_discovery_response.RunAssetDiscoveryResponse``: - Response of asset discovery run - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.RunAssetDiscoveryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.RunAssetDiscoveryRequest): - request = securitycenter_service.RunAssetDiscoveryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.run_asset_discovery] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - run_asset_discovery_response.RunAssetDiscoveryResponse, - metadata_type=empty.Empty, - ) - - # Done; return the response. - return response - - def set_finding_state( - self, - request: securitycenter_service.SetFindingStateRequest = None, - *, - name: str = None, - state: finding.Finding.State = None, - start_time: timestamp.Timestamp = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the state of a finding. - - Args: - request (:class:`~.securitycenter_service.SetFindingStateRequest`): - The request object. Request message for updating a - finding's state. - name (:class:`str`): - Required. The relative resource name of the finding. - See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - state (:class:`~.finding.Finding.State`): - Required. The desired State of the - finding. - This corresponds to the ``state`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - start_time (:class:`~.timestamp.Timestamp`): - Required. The time at which the - updated state takes effect. - This corresponds to the ``start_time`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.finding.Finding: - Security Command Center finding. - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, state, start_time]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.SetFindingStateRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.SetFindingStateRequest): - request = securitycenter_service.SetFindingStateRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - if state is not None: - request.state = state - if start_time is not None: - request.start_time = start_time - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_finding_state] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def set_iam_policy( - self, - request: iam_policy.SetIamPolicyRequest = None, - *, - resource: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: - r"""Sets the access control policy on the specified - Source. - - Args: - request (:class:`~.iam_policy.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - This corresponds to the ``resource`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - 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." - ) - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.SetIamPolicyRequest(**request) - - elif not request: - request = iam_policy.SetIamPolicyRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def test_iam_permissions( - self, - request: iam_policy.TestIamPermissionsRequest = None, - *, - resource: str = None, - permissions: Sequence[str] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: - r"""Returns the permissions that a caller has on the - specified source. - - Args: - request (:class:`~.iam_policy.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (:class:`Sequence[str]`): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - This corresponds to the ``permissions`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.iam_policy.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource, permissions]) - 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." - ) - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.TestIamPermissionsRequest(**request) - - elif not request: - request = iam_policy.TestIamPermissionsRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource - - if permissions: - request.permissions.extend(permissions) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def update_finding( - self, - request: securitycenter_service.UpdateFindingRequest = None, - *, - finding: gcs_finding.Finding = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Args: - request (:class:`~.securitycenter_service.UpdateFindingRequest`): - The request object. Request message for updating or - creating a finding. - finding (:class:`~.gcs_finding.Finding`): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the - name must be alphanumeric and less than or equal to 32 - characters and greater than 0 characters in length. - This corresponds to the ``finding`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_finding.Finding: - Security Command Center finding. - A finding is a record of assessment data - like security, risk, health, or privacy, - that is ingested into Security Command - Center for presentation, notification, - analysis, policy testing, and - enforcement. For example, a cross-site - scripting (XSS) vulnerability in an App - Engine application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([finding]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.UpdateFindingRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.UpdateFindingRequest): - request = securitycenter_service.UpdateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("finding.name", request.finding.name),) - ), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def update_notification_config( - self, - request: securitycenter_service.UpdateNotificationConfigRequest = None, - *, - notification_config: gcs_notification_config.NotificationConfig = None, - update_mask: field_mask.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Args: - request (:class:`~.securitycenter_service.UpdateNotificationConfigRequest`): - The request object. Request message for updating a - notification config. - notification_config (:class:`~.gcs_notification_config.NotificationConfig`): - Required. The notification config to - update. - This corresponds to the ``notification_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`~.field_mask.FieldMask`): - The FieldMask to use when updating - the notification config. - If empty all mutable fields will be - updated. - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_notification_config.NotificationConfig: - Cloud Security Command Center (Cloud - SCC) notification configs. - A notification config is a Cloud SCC - resource that contains the configuration - to send notifications for create/update - events of findings, assets and etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([notification_config, update_mask]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.UpdateNotificationConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance( - request, securitycenter_service.UpdateNotificationConfigRequest - ): - request = securitycenter_service.UpdateNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if notification_config is not None: - request.notification_config = notification_config - 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_notification_config - ] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("notification_config.name", request.notification_config.name),) - ), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def update_organization_settings( - self, - request: securitycenter_service.UpdateOrganizationSettingsRequest = None, - *, - organization_settings: gcs_organization_settings.OrganizationSettings = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Updates an organization's settings. - - Args: - request (:class:`~.securitycenter_service.UpdateOrganizationSettingsRequest`): - The request object. Request message for updating an - organization's settings. - organization_settings (:class:`~.gcs_organization_settings.OrganizationSettings`): - Required. The organization settings - resource to update. - This corresponds to the ``organization_settings`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_organization_settings.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([organization_settings]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.UpdateOrganizationSettingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance( - request, securitycenter_service.UpdateOrganizationSettingsRequest - ): - request = securitycenter_service.UpdateOrganizationSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if organization_settings is not None: - request.organization_settings = organization_settings - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.update_organization_settings - ] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("organization_settings.name", request.organization_settings.name),) - ), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def update_source( - self, - request: securitycenter_service.UpdateSourceRequest = None, - *, - source: gcs_source.Source = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Updates a source. - - Args: - request (:class:`~.securitycenter_service.UpdateSourceRequest`): - The request object. Request message for updating a - source. - source (:class:`~.gcs_source.Source`): - Required. The source resource to - update. - This corresponds to the ``source`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, and other tools. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([source]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.UpdateSourceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.UpdateSourceRequest): - request = securitycenter_service.UpdateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("source.name", request.source.name),) - ), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def update_security_marks( - self, - request: securitycenter_service.UpdateSecurityMarksRequest = None, - *, - security_marks: gcs_security_marks.SecurityMarks = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_security_marks.SecurityMarks: - r"""Updates security marks. - - Args: - request (:class:`~.securitycenter_service.UpdateSecurityMarksRequest`): - The request object. Request message for updating a - SecurityMarks resource. - security_marks (:class:`~.gcs_security_marks.SecurityMarks`): - Required. The security marks resource - to update. - This corresponds to the ``security_marks`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_security_marks.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_marks]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.UpdateSecurityMarksRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): - request = securitycenter_service.UpdateSecurityMarksRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if security_marks is not None: - request.security_marks = security_marks - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_security_marks] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("security_marks.name", request.security_marks.name),) - ), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -try: - _client_info = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-securitycenter", - ).version, - ) -except pkg_resources.DistributionNotFound: - _client_info = gapic_v1.client_info.ClientInfo() - - -__all__ = ("SecurityCenterClient",) diff --git a/google/cloud/securitycenter_v1/services/security_center/pagers.py b/google/cloud/securitycenter_v1/services/security_center/pagers.py deleted file mode 100644 index 98a0cc03..00000000 --- a/google/cloud/securitycenter_v1/services/security_center/pagers.py +++ /dev/null @@ -1,804 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple - -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import source - - -class GroupAssetsPager: - """A pager for iterating through ``group_assets`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.GroupAssetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``GroupAssets`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.GroupAssetsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., securitycenter_service.GroupAssetsResponse], - request: securitycenter_service.GroupAssetsRequest, - response: securitycenter_service.GroupAssetsResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.GroupAssetsRequest`): - The initial request object. - response (:class:`~.securitycenter_service.GroupAssetsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.GroupAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.GroupAssetsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[securitycenter_service.GroupResult]: - for page in self.pages: - yield from page.group_by_results - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class GroupAssetsAsyncPager: - """A pager for iterating through ``group_assets`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.GroupAssetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``GroupAssets`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.GroupAssetsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., Awaitable[securitycenter_service.GroupAssetsResponse]], - request: securitycenter_service.GroupAssetsRequest, - response: securitycenter_service.GroupAssetsResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.GroupAssetsRequest`): - The initial request object. - response (:class:`~.securitycenter_service.GroupAssetsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.GroupAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.GroupAssetsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[securitycenter_service.GroupResult]: - async def async_generator(): - async for page in self.pages: - for response in page.group_by_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class GroupFindingsPager: - """A pager for iterating through ``group_findings`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.GroupFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``GroupFindings`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.GroupFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., securitycenter_service.GroupFindingsResponse], - request: securitycenter_service.GroupFindingsRequest, - response: securitycenter_service.GroupFindingsResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.GroupFindingsRequest`): - The initial request object. - response (:class:`~.securitycenter_service.GroupFindingsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.GroupFindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.GroupFindingsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[securitycenter_service.GroupResult]: - for page in self.pages: - yield from page.group_by_results - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class GroupFindingsAsyncPager: - """A pager for iterating through ``group_findings`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.GroupFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``GroupFindings`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.GroupFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., Awaitable[securitycenter_service.GroupFindingsResponse]], - request: securitycenter_service.GroupFindingsRequest, - response: securitycenter_service.GroupFindingsResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.GroupFindingsRequest`): - The initial request object. - response (:class:`~.securitycenter_service.GroupFindingsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.GroupFindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages( - self, - ) -> AsyncIterable[securitycenter_service.GroupFindingsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[securitycenter_service.GroupResult]: - async def async_generator(): - async for page in self.pages: - for response in page.group_by_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListAssetsPager: - """A pager for iterating through ``list_assets`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.ListAssetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``list_assets_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAssets`` requests and continue to iterate - through the ``list_assets_results`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.ListAssetsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., securitycenter_service.ListAssetsResponse], - request: securitycenter_service.ListAssetsRequest, - response: securitycenter_service.ListAssetsResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.ListAssetsRequest`): - The initial request object. - response (:class:`~.securitycenter_service.ListAssetsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.ListAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.ListAssetsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__( - self, - ) -> Iterable[securitycenter_service.ListAssetsResponse.ListAssetsResult]: - for page in self.pages: - yield from page.list_assets_results - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListAssetsAsyncPager: - """A pager for iterating through ``list_assets`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.ListAssetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``list_assets_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAssets`` requests and continue to iterate - through the ``list_assets_results`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.ListAssetsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., Awaitable[securitycenter_service.ListAssetsResponse]], - request: securitycenter_service.ListAssetsRequest, - response: securitycenter_service.ListAssetsResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.ListAssetsRequest`): - The initial request object. - response (:class:`~.securitycenter_service.ListAssetsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.ListAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.ListAssetsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__( - self, - ) -> AsyncIterable[securitycenter_service.ListAssetsResponse.ListAssetsResult]: - async def async_generator(): - async for page in self.pages: - for response in page.list_assets_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListFindingsPager: - """A pager for iterating through ``list_findings`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.ListFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``list_findings_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``list_findings_results`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.ListFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., securitycenter_service.ListFindingsResponse], - request: securitycenter_service.ListFindingsRequest, - response: securitycenter_service.ListFindingsResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.ListFindingsRequest`): - The initial request object. - response (:class:`~.securitycenter_service.ListFindingsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.ListFindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.ListFindingsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__( - self, - ) -> Iterable[securitycenter_service.ListFindingsResponse.ListFindingsResult]: - for page in self.pages: - yield from page.list_findings_results - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListFindingsAsyncPager: - """A pager for iterating through ``list_findings`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.ListFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``list_findings_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``list_findings_results`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.ListFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., Awaitable[securitycenter_service.ListFindingsResponse]], - request: securitycenter_service.ListFindingsRequest, - response: securitycenter_service.ListFindingsResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.ListFindingsRequest`): - The initial request object. - response (:class:`~.securitycenter_service.ListFindingsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.ListFindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.ListFindingsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__( - self, - ) -> AsyncIterable[securitycenter_service.ListFindingsResponse.ListFindingsResult]: - async def async_generator(): - async for page in self.pages: - for response in page.list_findings_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListNotificationConfigsPager: - """A pager for iterating through ``list_notification_configs`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.ListNotificationConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``notification_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListNotificationConfigs`` requests and continue to iterate - through the ``notification_configs`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.ListNotificationConfigsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., securitycenter_service.ListNotificationConfigsResponse], - request: securitycenter_service.ListNotificationConfigsRequest, - response: securitycenter_service.ListNotificationConfigsResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.ListNotificationConfigsRequest`): - The initial request object. - response (:class:`~.securitycenter_service.ListNotificationConfigsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.ListNotificationConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.ListNotificationConfigsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[notification_config.NotificationConfig]: - for page in self.pages: - yield from page.notification_configs - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListNotificationConfigsAsyncPager: - """A pager for iterating through ``list_notification_configs`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.ListNotificationConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``notification_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListNotificationConfigs`` requests and continue to iterate - through the ``notification_configs`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.ListNotificationConfigsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[ - ..., Awaitable[securitycenter_service.ListNotificationConfigsResponse] - ], - request: securitycenter_service.ListNotificationConfigsRequest, - response: securitycenter_service.ListNotificationConfigsResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.ListNotificationConfigsRequest`): - The initial request object. - response (:class:`~.securitycenter_service.ListNotificationConfigsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.ListNotificationConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages( - self, - ) -> AsyncIterable[securitycenter_service.ListNotificationConfigsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[notification_config.NotificationConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.notification_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListSourcesPager: - """A pager for iterating through ``list_sources`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.ListSourcesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``sources`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSources`` requests and continue to iterate - through the ``sources`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.ListSourcesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., securitycenter_service.ListSourcesResponse], - request: securitycenter_service.ListSourcesRequest, - response: securitycenter_service.ListSourcesResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.ListSourcesRequest`): - The initial request object. - response (:class:`~.securitycenter_service.ListSourcesResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.ListSourcesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.ListSourcesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[source.Source]: - for page in self.pages: - yield from page.sources - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListSourcesAsyncPager: - """A pager for iterating through ``list_sources`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.ListSourcesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``sources`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSources`` requests and continue to iterate - through the ``sources`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.ListSourcesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., Awaitable[securitycenter_service.ListSourcesResponse]], - request: securitycenter_service.ListSourcesRequest, - response: securitycenter_service.ListSourcesResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.ListSourcesRequest`): - The initial request object. - response (:class:`~.securitycenter_service.ListSourcesResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.ListSourcesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.ListSourcesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[source.Source]: - async def async_generator(): - async for page in self.pages: - for response in page.sources: - yield response - - return async_generator() - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/securitycenter_v1/services/security_center/transports/__init__.py b/google/cloud/securitycenter_v1/services/security_center/transports/__init__.py deleted file mode 100644 index 20423f2a..00000000 --- a/google/cloud/securitycenter_v1/services/security_center/transports/__init__.py +++ /dev/null @@ -1,36 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 typing import Dict, Type - -from .base import SecurityCenterTransport -from .grpc import SecurityCenterGrpcTransport -from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] -_transport_registry["grpc"] = SecurityCenterGrpcTransport -_transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport - - -__all__ = ( - "SecurityCenterTransport", - "SecurityCenterGrpcTransport", - "SecurityCenterGrpcAsyncIOTransport", -) diff --git a/google/cloud/securitycenter_v1/services/security_center/transports/base.py b/google/cloud/securitycenter_v1/services/security_center/transports/base.py deleted file mode 100644 index c00ab831..00000000 --- a/google/cloud/securitycenter_v1/services/security_center/transports/base.py +++ /dev/null @@ -1,566 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 -import typing -import pkg_resources - -from google import auth -from google.api_core import exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore - -from google.cloud.securitycenter_v1.types import finding -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import ( - notification_config as gcs_notification_config, -) -from google.cloud.securitycenter_v1.types import organization_settings -from google.cloud.securitycenter_v1.types import ( - organization_settings as gcs_organization_settings, -) -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import source -from google.cloud.securitycenter_v1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - - -try: - _client_info = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-securitycenter", - ).version, - ) -except pkg_resources.DistributionNotFound: - _client_info = gapic_v1.client_info.ClientInfo() - - -class SecurityCenterTransport(abc.ABC): - """Abstract transport class for SecurityCenter.""" - - AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - - def __init__( - self, - *, - host: str = "securitycenter.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): The hostname to connect to. - 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]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) - - if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id - ) - - # Save the credentials. - self._credentials = credentials - - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages() - - def _prep_wrapped_messages(self): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_source: gapic_v1.method.wrap_method( - self.create_source, default_timeout=60.0, client_info=_client_info, - ), - self.create_finding: gapic_v1.method.wrap_method( - self.create_finding, default_timeout=60.0, client_info=_client_info, - ), - self.create_notification_config: gapic_v1.method.wrap_method( - self.create_notification_config, - default_timeout=60.0, - client_info=_client_info, - ), - self.delete_notification_config: gapic_v1.method.wrap_method( - self.delete_notification_config, - default_timeout=60.0, - client_info=_client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ), - self.get_notification_config: gapic_v1.method.wrap_method( - self.get_notification_config, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ), - self.get_organization_settings: gapic_v1.method.wrap_method( - self.get_organization_settings, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ), - self.get_source: gapic_v1.method.wrap_method( - self.get_source, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ), - self.group_assets: gapic_v1.method.wrap_method( - self.group_assets, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ), - self.group_findings: gapic_v1.method.wrap_method( - self.group_findings, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ), - self.list_assets: gapic_v1.method.wrap_method( - self.list_assets, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ), - self.list_findings: gapic_v1.method.wrap_method( - self.list_findings, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ), - self.list_notification_configs: gapic_v1.method.wrap_method( - self.list_notification_configs, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ), - self.list_sources: gapic_v1.method.wrap_method( - self.list_sources, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ), - self.run_asset_discovery: gapic_v1.method.wrap_method( - self.run_asset_discovery, - default_timeout=60.0, - client_info=_client_info, - ), - self.set_finding_state: gapic_v1.method.wrap_method( - self.set_finding_state, default_timeout=60.0, client_info=_client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, default_timeout=60.0, client_info=_client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.DeadlineExceeded, exceptions.ServiceUnavailable, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ), - self.update_finding: gapic_v1.method.wrap_method( - self.update_finding, default_timeout=60.0, client_info=_client_info, - ), - self.update_notification_config: gapic_v1.method.wrap_method( - self.update_notification_config, - default_timeout=60.0, - client_info=_client_info, - ), - self.update_organization_settings: gapic_v1.method.wrap_method( - self.update_organization_settings, - default_timeout=60.0, - client_info=_client_info, - ), - self.update_source: gapic_v1.method.wrap_method( - self.update_source, default_timeout=60.0, client_info=_client_info, - ), - self.update_security_marks: gapic_v1.method.wrap_method( - self.update_security_marks, - default_timeout=480.0, - client_info=_client_info, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_source( - self, - ) -> typing.Callable[ - [securitycenter_service.CreateSourceRequest], - typing.Union[gcs_source.Source, typing.Awaitable[gcs_source.Source]], - ]: - raise NotImplementedError() - - @property - def create_finding( - self, - ) -> typing.Callable[ - [securitycenter_service.CreateFindingRequest], - typing.Union[gcs_finding.Finding, typing.Awaitable[gcs_finding.Finding]], - ]: - raise NotImplementedError() - - @property - def create_notification_config( - self, - ) -> typing.Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - typing.Union[ - gcs_notification_config.NotificationConfig, - typing.Awaitable[gcs_notification_config.NotificationConfig], - ], - ]: - raise NotImplementedError() - - @property - def delete_notification_config( - self, - ) -> typing.Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], - ]: - raise NotImplementedError() - - @property - def get_iam_policy( - self, - ) -> typing.Callable[ - [iam_policy.GetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], - ]: - raise NotImplementedError() - - @property - def get_notification_config( - self, - ) -> typing.Callable[ - [securitycenter_service.GetNotificationConfigRequest], - typing.Union[ - notification_config.NotificationConfig, - typing.Awaitable[notification_config.NotificationConfig], - ], - ]: - raise NotImplementedError() - - @property - def get_organization_settings( - self, - ) -> typing.Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - typing.Union[ - organization_settings.OrganizationSettings, - typing.Awaitable[organization_settings.OrganizationSettings], - ], - ]: - raise NotImplementedError() - - @property - def get_source( - self, - ) -> typing.Callable[ - [securitycenter_service.GetSourceRequest], - typing.Union[source.Source, typing.Awaitable[source.Source]], - ]: - raise NotImplementedError() - - @property - def group_assets( - self, - ) -> typing.Callable[ - [securitycenter_service.GroupAssetsRequest], - typing.Union[ - securitycenter_service.GroupAssetsResponse, - typing.Awaitable[securitycenter_service.GroupAssetsResponse], - ], - ]: - raise NotImplementedError() - - @property - def group_findings( - self, - ) -> typing.Callable[ - [securitycenter_service.GroupFindingsRequest], - typing.Union[ - securitycenter_service.GroupFindingsResponse, - typing.Awaitable[securitycenter_service.GroupFindingsResponse], - ], - ]: - raise NotImplementedError() - - @property - def list_assets( - self, - ) -> typing.Callable[ - [securitycenter_service.ListAssetsRequest], - typing.Union[ - securitycenter_service.ListAssetsResponse, - typing.Awaitable[securitycenter_service.ListAssetsResponse], - ], - ]: - raise NotImplementedError() - - @property - def list_findings( - self, - ) -> typing.Callable[ - [securitycenter_service.ListFindingsRequest], - typing.Union[ - securitycenter_service.ListFindingsResponse, - typing.Awaitable[securitycenter_service.ListFindingsResponse], - ], - ]: - raise NotImplementedError() - - @property - def list_notification_configs( - self, - ) -> typing.Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - typing.Union[ - securitycenter_service.ListNotificationConfigsResponse, - typing.Awaitable[securitycenter_service.ListNotificationConfigsResponse], - ], - ]: - raise NotImplementedError() - - @property - def list_sources( - self, - ) -> typing.Callable[ - [securitycenter_service.ListSourcesRequest], - typing.Union[ - securitycenter_service.ListSourcesResponse, - typing.Awaitable[securitycenter_service.ListSourcesResponse], - ], - ]: - raise NotImplementedError() - - @property - def run_asset_discovery( - self, - ) -> typing.Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], - ]: - raise NotImplementedError() - - @property - def set_finding_state( - self, - ) -> typing.Callable[ - [securitycenter_service.SetFindingStateRequest], - typing.Union[finding.Finding, typing.Awaitable[finding.Finding]], - ]: - raise NotImplementedError() - - @property - def set_iam_policy( - self, - ) -> typing.Callable[ - [iam_policy.SetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], - ]: - raise NotImplementedError() - - @property - def test_iam_permissions( - self, - ) -> typing.Callable[ - [iam_policy.TestIamPermissionsRequest], - typing.Union[ - iam_policy.TestIamPermissionsResponse, - typing.Awaitable[iam_policy.TestIamPermissionsResponse], - ], - ]: - raise NotImplementedError() - - @property - def update_finding( - self, - ) -> typing.Callable[ - [securitycenter_service.UpdateFindingRequest], - typing.Union[gcs_finding.Finding, typing.Awaitable[gcs_finding.Finding]], - ]: - raise NotImplementedError() - - @property - def update_notification_config( - self, - ) -> typing.Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - typing.Union[ - gcs_notification_config.NotificationConfig, - typing.Awaitable[gcs_notification_config.NotificationConfig], - ], - ]: - raise NotImplementedError() - - @property - def update_organization_settings( - self, - ) -> typing.Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - typing.Union[ - gcs_organization_settings.OrganizationSettings, - typing.Awaitable[gcs_organization_settings.OrganizationSettings], - ], - ]: - raise NotImplementedError() - - @property - def update_source( - self, - ) -> typing.Callable[ - [securitycenter_service.UpdateSourceRequest], - typing.Union[gcs_source.Source, typing.Awaitable[gcs_source.Source]], - ]: - raise NotImplementedError() - - @property - def update_security_marks( - self, - ) -> typing.Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - typing.Union[ - gcs_security_marks.SecurityMarks, - typing.Awaitable[gcs_security_marks.SecurityMarks], - ], - ]: - raise NotImplementedError() - - -__all__ = ("SecurityCenterTransport",) diff --git a/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py b/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py deleted file mode 100644 index 5e5e3b95..00000000 --- a/google/cloud/securitycenter_v1/services/security_center/transports/grpc.py +++ /dev/null @@ -1,900 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 typing import Callable, Dict, Optional, Sequence, Tuple - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - - -import grpc # type: ignore - -from google.cloud.securitycenter_v1.types import finding -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import ( - notification_config as gcs_notification_config, -) -from google.cloud.securitycenter_v1.types import organization_settings -from google.cloud.securitycenter_v1.types import ( - organization_settings as gcs_organization_settings, -) -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import source -from google.cloud.securitycenter_v1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - -from .base import SecurityCenterTransport - - -class SecurityCenterGrpcTransport(SecurityCenterTransport): - """gRPC backend transport for SecurityCenter. - - V1 APIs for Security Center service. - - 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 = "securitycenter.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): The hostname to connect to. - 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 ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): 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 applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 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. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - - 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. - """ - if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. - credentials = False - - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - ) - - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - ) - - @classmethod - def create_channel( - cls, - host: str = "securitycenter.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs - ) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - address (Optionsl[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]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional 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. - """ - scopes = scopes or cls.AUTH_SCOPES - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Sanity check: Only create a new channel if we do not already - # have one. - if not hasattr(self, "_grpc_channel"): - self._grpc_channel = self.create_channel( - self._host, credentials=self._credentials, - ) - - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if "operations_client" not in self.__dict__: - self.__dict__["operations_client"] = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self.__dict__["operations_client"] - - @property - def create_source( - self, - ) -> Callable[[securitycenter_service.CreateSourceRequest], gcs_source.Source]: - r"""Return a callable for the create source method over gRPC. - - Creates a source. - - Returns: - Callable[[~.CreateSourceRequest], - ~.Source]: - 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_source" not in self._stubs: - self._stubs["create_source"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/CreateSource", - request_serializer=securitycenter_service.CreateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs["create_source"] - - @property - def create_finding( - self, - ) -> Callable[[securitycenter_service.CreateFindingRequest], gcs_finding.Finding]: - r"""Return a callable for the create finding method over gRPC. - - Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Returns: - Callable[[~.CreateFindingRequest], - ~.Finding]: - 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_finding" not in self._stubs: - self._stubs["create_finding"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/CreateFinding", - request_serializer=securitycenter_service.CreateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs["create_finding"] - - @property - def create_notification_config( - self, - ) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - gcs_notification_config.NotificationConfig, - ]: - r"""Return a callable for the create notification config method over gRPC. - - Creates a notification config. - - Returns: - Callable[[~.CreateNotificationConfigRequest], - ~.NotificationConfig]: - 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_notification_config" not in self._stubs: - self._stubs["create_notification_config"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/CreateNotificationConfig", - request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs["create_notification_config"] - - @property - def delete_notification_config( - self, - ) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], empty.Empty - ]: - r"""Return a callable for the delete notification config method over gRPC. - - Deletes a notification config. - - Returns: - Callable[[~.DeleteNotificationConfigRequest], - ~.Empty]: - 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 "delete_notification_config" not in self._stubs: - self._stubs["delete_notification_config"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/DeleteNotificationConfig", - request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, - response_deserializer=empty.Empty.FromString, - ) - return self._stubs["delete_notification_config"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy.GetIamPolicyRequest], policy.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the access control policy on the specified - Source. - - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - 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 "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/GetIamPolicy", - request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def get_notification_config( - self, - ) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - notification_config.NotificationConfig, - ]: - r"""Return a callable for the get notification config method over gRPC. - - Gets a notification config. - - Returns: - Callable[[~.GetNotificationConfigRequest], - ~.NotificationConfig]: - 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 "get_notification_config" not in self._stubs: - self._stubs["get_notification_config"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/GetNotificationConfig", - request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, - response_deserializer=notification_config.NotificationConfig.deserialize, - ) - return self._stubs["get_notification_config"] - - @property - def get_organization_settings( - self, - ) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - organization_settings.OrganizationSettings, - ]: - r"""Return a callable for the get organization settings method over gRPC. - - Gets the settings for an organization. - - Returns: - Callable[[~.GetOrganizationSettingsRequest], - ~.OrganizationSettings]: - 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 "get_organization_settings" not in self._stubs: - self._stubs["get_organization_settings"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/GetOrganizationSettings", - request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, - response_deserializer=organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs["get_organization_settings"] - - @property - def get_source( - self, - ) -> Callable[[securitycenter_service.GetSourceRequest], source.Source]: - r"""Return a callable for the get source method over gRPC. - - Gets a source. - - Returns: - Callable[[~.GetSourceRequest], - ~.Source]: - 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 "get_source" not in self._stubs: - self._stubs["get_source"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/GetSource", - request_serializer=securitycenter_service.GetSourceRequest.serialize, - response_deserializer=source.Source.deserialize, - ) - return self._stubs["get_source"] - - @property - def group_assets( - self, - ) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - securitycenter_service.GroupAssetsResponse, - ]: - r"""Return a callable for the group assets method over gRPC. - - Filters an organization's assets and groups them by - their specified properties. - - Returns: - Callable[[~.GroupAssetsRequest], - ~.GroupAssetsResponse]: - 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 "group_assets" not in self._stubs: - self._stubs["group_assets"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/GroupAssets", - request_serializer=securitycenter_service.GroupAssetsRequest.serialize, - response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, - ) - return self._stubs["group_assets"] - - @property - def group_findings( - self, - ) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - securitycenter_service.GroupFindingsResponse, - ]: - r"""Return a callable for the group findings method over gRPC. - - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings - - Returns: - Callable[[~.GroupFindingsRequest], - ~.GroupFindingsResponse]: - 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 "group_findings" not in self._stubs: - self._stubs["group_findings"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/GroupFindings", - request_serializer=securitycenter_service.GroupFindingsRequest.serialize, - response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, - ) - return self._stubs["group_findings"] - - @property - def list_assets( - self, - ) -> Callable[ - [securitycenter_service.ListAssetsRequest], - securitycenter_service.ListAssetsResponse, - ]: - r"""Return a callable for the list assets method over gRPC. - - Lists an organization's assets. - - Returns: - Callable[[~.ListAssetsRequest], - ~.ListAssetsResponse]: - 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 "list_assets" not in self._stubs: - self._stubs["list_assets"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/ListAssets", - request_serializer=securitycenter_service.ListAssetsRequest.serialize, - response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, - ) - return self._stubs["list_assets"] - - @property - def list_findings( - self, - ) -> Callable[ - [securitycenter_service.ListFindingsRequest], - securitycenter_service.ListFindingsResponse, - ]: - r"""Return a callable for the list findings method over gRPC. - - Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings - - Returns: - Callable[[~.ListFindingsRequest], - ~.ListFindingsResponse]: - 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 "list_findings" not in self._stubs: - self._stubs["list_findings"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/ListFindings", - request_serializer=securitycenter_service.ListFindingsRequest.serialize, - response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, - ) - return self._stubs["list_findings"] - - @property - def list_notification_configs( - self, - ) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - securitycenter_service.ListNotificationConfigsResponse, - ]: - r"""Return a callable for the list notification configs method over gRPC. - - Lists notification configs. - - Returns: - Callable[[~.ListNotificationConfigsRequest], - ~.ListNotificationConfigsResponse]: - 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 "list_notification_configs" not in self._stubs: - self._stubs["list_notification_configs"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/ListNotificationConfigs", - request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, - ) - return self._stubs["list_notification_configs"] - - @property - def list_sources( - self, - ) -> Callable[ - [securitycenter_service.ListSourcesRequest], - securitycenter_service.ListSourcesResponse, - ]: - r"""Return a callable for the list sources method over gRPC. - - Lists all sources belonging to an organization. - - Returns: - Callable[[~.ListSourcesRequest], - ~.ListSourcesResponse]: - 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 "list_sources" not in self._stubs: - self._stubs["list_sources"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/ListSources", - request_serializer=securitycenter_service.ListSourcesRequest.serialize, - response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, - ) - return self._stubs["list_sources"] - - @property - def run_asset_discovery( - self, - ) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], operations.Operation - ]: - r"""Return a callable for the run asset discovery method over gRPC. - - Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Returns: - Callable[[~.RunAssetDiscoveryRequest], - ~.Operation]: - 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 "run_asset_discovery" not in self._stubs: - self._stubs["run_asset_discovery"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/RunAssetDiscovery", - request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations.Operation.FromString, - ) - return self._stubs["run_asset_discovery"] - - @property - def set_finding_state( - self, - ) -> Callable[[securitycenter_service.SetFindingStateRequest], finding.Finding]: - r"""Return a callable for the set finding state method over gRPC. - - Updates the state of a finding. - - Returns: - Callable[[~.SetFindingStateRequest], - ~.Finding]: - 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 "set_finding_state" not in self._stubs: - self._stubs["set_finding_state"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/SetFindingState", - request_serializer=securitycenter_service.SetFindingStateRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs["set_finding_state"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], policy.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets the access control policy on the specified - Source. - - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - 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 "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/SetIamPolicy", - request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], iam_policy.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - - Returns the permissions that a caller has on the - specified source. - - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - 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 "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/TestIamPermissions", - request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - @property - def update_finding( - self, - ) -> Callable[[securitycenter_service.UpdateFindingRequest], gcs_finding.Finding]: - r"""Return a callable for the update finding method over gRPC. - - Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Returns: - Callable[[~.UpdateFindingRequest], - ~.Finding]: - 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_finding" not in self._stubs: - self._stubs["update_finding"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/UpdateFinding", - request_serializer=securitycenter_service.UpdateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs["update_finding"] - - @property - def update_notification_config( - self, - ) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - gcs_notification_config.NotificationConfig, - ]: - r"""Return a callable for the update notification config method over gRPC. - - Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Returns: - Callable[[~.UpdateNotificationConfigRequest], - ~.NotificationConfig]: - 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_notification_config" not in self._stubs: - self._stubs["update_notification_config"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/UpdateNotificationConfig", - request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs["update_notification_config"] - - @property - def update_organization_settings( - self, - ) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - gcs_organization_settings.OrganizationSettings, - ]: - r"""Return a callable for the update organization settings method over gRPC. - - Updates an organization's settings. - - Returns: - Callable[[~.UpdateOrganizationSettingsRequest], - ~.OrganizationSettings]: - 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_organization_settings" not in self._stubs: - self._stubs["update_organization_settings"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/UpdateOrganizationSettings", - request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, - response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs["update_organization_settings"] - - @property - def update_source( - self, - ) -> Callable[[securitycenter_service.UpdateSourceRequest], gcs_source.Source]: - r"""Return a callable for the update source method over gRPC. - - Updates a source. - - Returns: - Callable[[~.UpdateSourceRequest], - ~.Source]: - 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_source" not in self._stubs: - self._stubs["update_source"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/UpdateSource", - request_serializer=securitycenter_service.UpdateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs["update_source"] - - @property - def update_security_marks( - self, - ) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - gcs_security_marks.SecurityMarks, - ]: - r"""Return a callable for the update security marks method over gRPC. - - Updates security marks. - - Returns: - Callable[[~.UpdateSecurityMarksRequest], - ~.SecurityMarks]: - 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_security_marks" not in self._stubs: - self._stubs["update_security_marks"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/UpdateSecurityMarks", - request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, - response_deserializer=gcs_security_marks.SecurityMarks.deserialize, - ) - return self._stubs["update_security_marks"] - - -__all__ = ("SecurityCenterGrpcTransport",) diff --git a/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py b/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py deleted file mode 100644 index e362f98a..00000000 --- a/google/cloud/securitycenter_v1/services/security_center/transports/grpc_asyncio.py +++ /dev/null @@ -1,905 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple - -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.securitycenter_v1.types import finding -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import notification_config -from google.cloud.securitycenter_v1.types import ( - notification_config as gcs_notification_config, -) -from google.cloud.securitycenter_v1.types import organization_settings -from google.cloud.securitycenter_v1.types import ( - organization_settings as gcs_organization_settings, -) -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import securitycenter_service -from google.cloud.securitycenter_v1.types import source -from google.cloud.securitycenter_v1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - -from .base import SecurityCenterTransport -from .grpc import SecurityCenterGrpcTransport - - -class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): - """gRPC AsyncIO backend transport for SecurityCenter. - - V1 APIs for Security Center service. - - 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 = "securitycenter.googleapis.com", - credentials: 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: - address (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]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional 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. - """ - scopes = scopes or cls.AUTH_SCOPES - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - **kwargs, - ) - - def __init__( - self, - *, - host: str = "securitycenter.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): The hostname to connect to. - 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 ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional 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[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): 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 applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 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. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - - 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. - """ - if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. - credentials = False - - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - ) - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - ) - - self._stubs = {} - - @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. - """ - # Sanity check: Only create a new channel if we do not already - # have one. - if not hasattr(self, "_grpc_channel"): - self._grpc_channel = self.create_channel( - self._host, credentials=self._credentials, - ) - - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if "operations_client" not in self.__dict__: - self.__dict__["operations_client"] = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self.__dict__["operations_client"] - - @property - def create_source( - self, - ) -> Callable[ - [securitycenter_service.CreateSourceRequest], Awaitable[gcs_source.Source] - ]: - r"""Return a callable for the create source method over gRPC. - - Creates a source. - - Returns: - Callable[[~.CreateSourceRequest], - Awaitable[~.Source]]: - 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_source" not in self._stubs: - self._stubs["create_source"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/CreateSource", - request_serializer=securitycenter_service.CreateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs["create_source"] - - @property - def create_finding( - self, - ) -> Callable[ - [securitycenter_service.CreateFindingRequest], Awaitable[gcs_finding.Finding] - ]: - r"""Return a callable for the create finding method over gRPC. - - Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Returns: - Callable[[~.CreateFindingRequest], - Awaitable[~.Finding]]: - 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_finding" not in self._stubs: - self._stubs["create_finding"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/CreateFinding", - request_serializer=securitycenter_service.CreateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs["create_finding"] - - @property - def create_notification_config( - self, - ) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - Awaitable[gcs_notification_config.NotificationConfig], - ]: - r"""Return a callable for the create notification config method over gRPC. - - Creates a notification config. - - Returns: - Callable[[~.CreateNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - 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_notification_config" not in self._stubs: - self._stubs["create_notification_config"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/CreateNotificationConfig", - request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs["create_notification_config"] - - @property - def delete_notification_config( - self, - ) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], Awaitable[empty.Empty] - ]: - r"""Return a callable for the delete notification config method over gRPC. - - Deletes a notification config. - - Returns: - Callable[[~.DeleteNotificationConfigRequest], - Awaitable[~.Empty]]: - 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 "delete_notification_config" not in self._stubs: - self._stubs["delete_notification_config"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/DeleteNotificationConfig", - request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, - response_deserializer=empty.Empty.FromString, - ) - return self._stubs["delete_notification_config"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy.GetIamPolicyRequest], Awaitable[policy.Policy]]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the access control policy on the specified - Source. - - Returns: - Callable[[~.GetIamPolicyRequest], - Awaitable[~.Policy]]: - 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 "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/GetIamPolicy", - request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def get_notification_config( - self, - ) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - Awaitable[notification_config.NotificationConfig], - ]: - r"""Return a callable for the get notification config method over gRPC. - - Gets a notification config. - - Returns: - Callable[[~.GetNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - 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 "get_notification_config" not in self._stubs: - self._stubs["get_notification_config"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/GetNotificationConfig", - request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, - response_deserializer=notification_config.NotificationConfig.deserialize, - ) - return self._stubs["get_notification_config"] - - @property - def get_organization_settings( - self, - ) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - Awaitable[organization_settings.OrganizationSettings], - ]: - r"""Return a callable for the get organization settings method over gRPC. - - Gets the settings for an organization. - - Returns: - Callable[[~.GetOrganizationSettingsRequest], - Awaitable[~.OrganizationSettings]]: - 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 "get_organization_settings" not in self._stubs: - self._stubs["get_organization_settings"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/GetOrganizationSettings", - request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, - response_deserializer=organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs["get_organization_settings"] - - @property - def get_source( - self, - ) -> Callable[[securitycenter_service.GetSourceRequest], Awaitable[source.Source]]: - r"""Return a callable for the get source method over gRPC. - - Gets a source. - - Returns: - Callable[[~.GetSourceRequest], - Awaitable[~.Source]]: - 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 "get_source" not in self._stubs: - self._stubs["get_source"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/GetSource", - request_serializer=securitycenter_service.GetSourceRequest.serialize, - response_deserializer=source.Source.deserialize, - ) - return self._stubs["get_source"] - - @property - def group_assets( - self, - ) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - Awaitable[securitycenter_service.GroupAssetsResponse], - ]: - r"""Return a callable for the group assets method over gRPC. - - Filters an organization's assets and groups them by - their specified properties. - - Returns: - Callable[[~.GroupAssetsRequest], - Awaitable[~.GroupAssetsResponse]]: - 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 "group_assets" not in self._stubs: - self._stubs["group_assets"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/GroupAssets", - request_serializer=securitycenter_service.GroupAssetsRequest.serialize, - response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, - ) - return self._stubs["group_assets"] - - @property - def group_findings( - self, - ) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - Awaitable[securitycenter_service.GroupFindingsResponse], - ]: - r"""Return a callable for the group findings method over gRPC. - - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings - - Returns: - Callable[[~.GroupFindingsRequest], - Awaitable[~.GroupFindingsResponse]]: - 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 "group_findings" not in self._stubs: - self._stubs["group_findings"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/GroupFindings", - request_serializer=securitycenter_service.GroupFindingsRequest.serialize, - response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, - ) - return self._stubs["group_findings"] - - @property - def list_assets( - self, - ) -> Callable[ - [securitycenter_service.ListAssetsRequest], - Awaitable[securitycenter_service.ListAssetsResponse], - ]: - r"""Return a callable for the list assets method over gRPC. - - Lists an organization's assets. - - Returns: - Callable[[~.ListAssetsRequest], - Awaitable[~.ListAssetsResponse]]: - 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 "list_assets" not in self._stubs: - self._stubs["list_assets"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/ListAssets", - request_serializer=securitycenter_service.ListAssetsRequest.serialize, - response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, - ) - return self._stubs["list_assets"] - - @property - def list_findings( - self, - ) -> Callable[ - [securitycenter_service.ListFindingsRequest], - Awaitable[securitycenter_service.ListFindingsResponse], - ]: - r"""Return a callable for the list findings method over gRPC. - - Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: /v1/organizations/{organization_id}/sources/-/findings - - Returns: - Callable[[~.ListFindingsRequest], - Awaitable[~.ListFindingsResponse]]: - 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 "list_findings" not in self._stubs: - self._stubs["list_findings"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/ListFindings", - request_serializer=securitycenter_service.ListFindingsRequest.serialize, - response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, - ) - return self._stubs["list_findings"] - - @property - def list_notification_configs( - self, - ) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - Awaitable[securitycenter_service.ListNotificationConfigsResponse], - ]: - r"""Return a callable for the list notification configs method over gRPC. - - Lists notification configs. - - Returns: - Callable[[~.ListNotificationConfigsRequest], - Awaitable[~.ListNotificationConfigsResponse]]: - 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 "list_notification_configs" not in self._stubs: - self._stubs["list_notification_configs"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/ListNotificationConfigs", - request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, - ) - return self._stubs["list_notification_configs"] - - @property - def list_sources( - self, - ) -> Callable[ - [securitycenter_service.ListSourcesRequest], - Awaitable[securitycenter_service.ListSourcesResponse], - ]: - r"""Return a callable for the list sources method over gRPC. - - Lists all sources belonging to an organization. - - Returns: - Callable[[~.ListSourcesRequest], - Awaitable[~.ListSourcesResponse]]: - 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 "list_sources" not in self._stubs: - self._stubs["list_sources"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/ListSources", - request_serializer=securitycenter_service.ListSourcesRequest.serialize, - response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, - ) - return self._stubs["list_sources"] - - @property - def run_asset_discovery( - self, - ) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - Awaitable[operations.Operation], - ]: - r"""Return a callable for the run asset discovery method over gRPC. - - Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Returns: - Callable[[~.RunAssetDiscoveryRequest], - Awaitable[~.Operation]]: - 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 "run_asset_discovery" not in self._stubs: - self._stubs["run_asset_discovery"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/RunAssetDiscovery", - request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations.Operation.FromString, - ) - return self._stubs["run_asset_discovery"] - - @property - def set_finding_state( - self, - ) -> Callable[ - [securitycenter_service.SetFindingStateRequest], Awaitable[finding.Finding] - ]: - r"""Return a callable for the set finding state method over gRPC. - - Updates the state of a finding. - - Returns: - Callable[[~.SetFindingStateRequest], - Awaitable[~.Finding]]: - 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 "set_finding_state" not in self._stubs: - self._stubs["set_finding_state"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/SetFindingState", - request_serializer=securitycenter_service.SetFindingStateRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs["set_finding_state"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], Awaitable[policy.Policy]]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets the access control policy on the specified - Source. - - Returns: - Callable[[~.SetIamPolicyRequest], - Awaitable[~.Policy]]: - 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 "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/SetIamPolicy", - request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], - Awaitable[iam_policy.TestIamPermissionsResponse], - ]: - r"""Return a callable for the test iam permissions method over gRPC. - - Returns the permissions that a caller has on the - specified source. - - Returns: - Callable[[~.TestIamPermissionsRequest], - Awaitable[~.TestIamPermissionsResponse]]: - 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 "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/TestIamPermissions", - request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - @property - def update_finding( - self, - ) -> Callable[ - [securitycenter_service.UpdateFindingRequest], Awaitable[gcs_finding.Finding] - ]: - r"""Return a callable for the update finding method over gRPC. - - Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Returns: - Callable[[~.UpdateFindingRequest], - Awaitable[~.Finding]]: - 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_finding" not in self._stubs: - self._stubs["update_finding"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/UpdateFinding", - request_serializer=securitycenter_service.UpdateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs["update_finding"] - - @property - def update_notification_config( - self, - ) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - Awaitable[gcs_notification_config.NotificationConfig], - ]: - r"""Return a callable for the update notification config method over gRPC. - - Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Returns: - Callable[[~.UpdateNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - 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_notification_config" not in self._stubs: - self._stubs["update_notification_config"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/UpdateNotificationConfig", - request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs["update_notification_config"] - - @property - def update_organization_settings( - self, - ) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - Awaitable[gcs_organization_settings.OrganizationSettings], - ]: - r"""Return a callable for the update organization settings method over gRPC. - - Updates an organization's settings. - - Returns: - Callable[[~.UpdateOrganizationSettingsRequest], - Awaitable[~.OrganizationSettings]]: - 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_organization_settings" not in self._stubs: - self._stubs["update_organization_settings"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/UpdateOrganizationSettings", - request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, - response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs["update_organization_settings"] - - @property - def update_source( - self, - ) -> Callable[ - [securitycenter_service.UpdateSourceRequest], Awaitable[gcs_source.Source] - ]: - r"""Return a callable for the update source method over gRPC. - - Updates a source. - - Returns: - Callable[[~.UpdateSourceRequest], - Awaitable[~.Source]]: - 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_source" not in self._stubs: - self._stubs["update_source"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/UpdateSource", - request_serializer=securitycenter_service.UpdateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs["update_source"] - - @property - def update_security_marks( - self, - ) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - Awaitable[gcs_security_marks.SecurityMarks], - ]: - r"""Return a callable for the update security marks method over gRPC. - - Updates security marks. - - Returns: - Callable[[~.UpdateSecurityMarksRequest], - Awaitable[~.SecurityMarks]]: - 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_security_marks" not in self._stubs: - self._stubs["update_security_marks"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1.SecurityCenter/UpdateSecurityMarks", - request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, - response_deserializer=gcs_security_marks.SecurityMarks.deserialize, - ) - return self._stubs["update_security_marks"] - - -__all__ = ("SecurityCenterGrpcAsyncIOTransport",) diff --git a/google/cloud/securitycenter_v1/types/__init__.py b/google/cloud/securitycenter_v1/types/__init__.py deleted file mode 100644 index c65c45b8..00000000 --- a/google/cloud/securitycenter_v1/types/__init__.py +++ /dev/null @@ -1,95 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 .security_marks import SecurityMarks -from .asset import Asset -from .finding import Finding -from .notification_config import NotificationConfig -from .resource import Resource -from .notification_message import NotificationMessage -from .organization_settings import OrganizationSettings -from .run_asset_discovery_response import RunAssetDiscoveryResponse -from .source import Source -from .securitycenter_service import ( - CreateFindingRequest, - CreateNotificationConfigRequest, - CreateSourceRequest, - DeleteNotificationConfigRequest, - GetNotificationConfigRequest, - GetOrganizationSettingsRequest, - GetSourceRequest, - GroupAssetsRequest, - GroupAssetsResponse, - GroupFindingsRequest, - GroupFindingsResponse, - GroupResult, - ListNotificationConfigsRequest, - ListNotificationConfigsResponse, - ListSourcesRequest, - ListSourcesResponse, - ListAssetsRequest, - ListAssetsResponse, - ListFindingsRequest, - ListFindingsResponse, - SetFindingStateRequest, - RunAssetDiscoveryRequest, - UpdateFindingRequest, - UpdateNotificationConfigRequest, - UpdateOrganizationSettingsRequest, - UpdateSourceRequest, - UpdateSecurityMarksRequest, -) - - -__all__ = ( - "SecurityMarks", - "Asset", - "Finding", - "NotificationConfig", - "Resource", - "NotificationMessage", - "OrganizationSettings", - "RunAssetDiscoveryResponse", - "Source", - "CreateFindingRequest", - "CreateNotificationConfigRequest", - "CreateSourceRequest", - "DeleteNotificationConfigRequest", - "GetNotificationConfigRequest", - "GetOrganizationSettingsRequest", - "GetSourceRequest", - "GroupAssetsRequest", - "GroupAssetsResponse", - "GroupFindingsRequest", - "GroupFindingsResponse", - "GroupResult", - "ListNotificationConfigsRequest", - "ListNotificationConfigsResponse", - "ListSourcesRequest", - "ListSourcesResponse", - "ListAssetsRequest", - "ListAssetsResponse", - "ListFindingsRequest", - "ListFindingsResponse", - "SetFindingStateRequest", - "RunAssetDiscoveryRequest", - "UpdateFindingRequest", - "UpdateNotificationConfigRequest", - "UpdateOrganizationSettingsRequest", - "UpdateSourceRequest", - "UpdateSecurityMarksRequest", -) diff --git a/google/cloud/securitycenter_v1/types/asset.py b/google/cloud/securitycenter_v1/types/asset.py deleted file mode 100644 index d1992e53..00000000 --- a/google/cloud/securitycenter_v1/types/asset.py +++ /dev/null @@ -1,166 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 proto # type: ignore - - -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - - -__protobuf__ = proto.module( - package="google.cloud.securitycenter.v1", manifest={"Asset",}, -) - - -class Asset(proto.Message): - r"""Security Command Center representation of a Google Cloud - resource. - - The Asset is a Security Command Center resource that captures - information about a single Google Cloud resource. All - modifications to an Asset are only within the context of - Security Command Center and don't affect the referenced Google - Cloud resource. - - Attributes: - name (str): - The relative resource name of this asset. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/assets/{asset_id}". - security_center_properties (~.asset.Asset.SecurityCenterProperties): - Security Command Center managed properties. - These properties are managed by Security Command - Center and cannot be modified by the user. - resource_properties (Sequence[~.asset.Asset.ResourcePropertiesEntry]): - Resource managed properties. These properties - are managed and defined by the Google Cloud - resource and cannot be modified by the user. - security_marks (~.gcs_security_marks.SecurityMarks): - User specified security marks. These marks - are entirely managed by the user and come from - the SecurityMarks resource that belongs to the - asset. - create_time (~.timestamp.Timestamp): - The time at which the asset was created in - Security Command Center. - update_time (~.timestamp.Timestamp): - The time at which the asset was last updated, - added, or deleted in Security Command Center. - iam_policy (~.asset.Asset.IamPolicy): - Cloud IAM Policy information associated with - the Google Cloud resource described by the - Security Command Center asset. This information - is managed and defined by the Google Cloud - resource and cannot be modified by the user. - """ - - class SecurityCenterProperties(proto.Message): - r"""Security Command Center managed properties. These properties - are managed by Security Command Center and cannot be modified by - the user. - - Attributes: - resource_name (str): - The full resource name of the Google Cloud resource this - asset represents. This field is immutable after create time. - See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_type (str): - The type of the Google Cloud resource. - Examples include: APPLICATION, PROJECT, and - ORGANIZATION. This is a case insensitive field - defined by Security Command Center and/or the - producer of the resource and is immutable after - create time. - resource_parent (str): - The full resource name of the immediate parent of the - resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_project (str): - The full resource name of the project the resource belongs - to. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_owners (Sequence[str]): - Owners of the Google Cloud resource. - resource_display_name (str): - The user defined display name for this - resource. - resource_parent_display_name (str): - The user defined display name for the parent - of this resource. - resource_project_display_name (str): - The user defined display name for the project - of this resource. - """ - - resource_name = proto.Field(proto.STRING, number=1) - - resource_type = proto.Field(proto.STRING, number=2) - - resource_parent = proto.Field(proto.STRING, number=3) - - resource_project = proto.Field(proto.STRING, number=4) - - resource_owners = proto.RepeatedField(proto.STRING, number=5) - - resource_display_name = proto.Field(proto.STRING, number=6) - - resource_parent_display_name = proto.Field(proto.STRING, number=7) - - resource_project_display_name = proto.Field(proto.STRING, number=8) - - class IamPolicy(proto.Message): - r"""Cloud IAM Policy information associated with the Google Cloud - resource described by the Security Command Center asset. This - information is managed and defined by the Google Cloud resource - and cannot be modified by the user. - - Attributes: - policy_blob (str): - The JSON representation of the Policy - associated with the asset. See - https://cloud.google.com/iam/reference/rest/v1/Policy - for format details. - """ - - policy_blob = proto.Field(proto.STRING, number=1) - - name = proto.Field(proto.STRING, number=1) - - security_center_properties = proto.Field( - proto.MESSAGE, number=2, message=SecurityCenterProperties, - ) - - resource_properties = proto.MapField( - proto.STRING, proto.MESSAGE, number=7, message=struct.Value, - ) - - security_marks = proto.Field( - proto.MESSAGE, number=8, message=gcs_security_marks.SecurityMarks, - ) - - create_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) - - update_time = proto.Field(proto.MESSAGE, number=10, message=timestamp.Timestamp,) - - iam_policy = proto.Field(proto.MESSAGE, number=11, message=IamPolicy,) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/finding.py b/google/cloud/securitycenter_v1/types/finding.py deleted file mode 100644 index c7a5dbdc..00000000 --- a/google/cloud/securitycenter_v1/types/finding.py +++ /dev/null @@ -1,123 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 proto # type: ignore - - -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - - -__protobuf__ = proto.module( - package="google.cloud.securitycenter.v1", manifest={"Finding",}, -) - - -class Finding(proto.Message): - r"""Security Command Center finding. - A finding is a record of assessment data like security, risk, - health, or privacy, that is ingested into Security Command - Center for presentation, notification, analysis, policy testing, - and enforcement. For example, a cross-site scripting (XSS) - vulnerability in an App Engine application is a finding. - - Attributes: - name (str): - The relative resource name of this finding. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}". - parent (str): - The relative resource name of the source the finding belongs - to. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - This field is immutable after creation time. For example: - "organizations/{organization_id}/sources/{source_id}". - resource_name (str): - For findings on Google Cloud resources, the full resource - name of the Google Cloud resource this finding is for. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - When the finding is for a non-Google Cloud resource, the - resourceName can be a customer or partner defined string. - This field is immutable after creation time. - state (~.finding.Finding.State): - The state of the finding. - category (str): - The additional taxonomy group within findings from a given - source. This field is immutable after creation time. - Example: "XSS_FLASH_INJECTION". - external_uri (str): - The URI that, if available, points to a web - page outside of Security Command Center where - additional information about the finding can be - found. This field is guaranteed to be either - empty or a well formed URL. - source_properties (Sequence[~.finding.Finding.SourcePropertiesEntry]): - Source specific properties. These properties are managed by - the source that writes the finding. The key names in the - source_properties map must be between 1 and 255 characters, - and must start with a letter and contain alphanumeric - characters or underscores only. - security_marks (~.gcs_security_marks.SecurityMarks): - Output only. User specified security marks. - These marks are entirely managed by the user and - come from the SecurityMarks resource that - belongs to the finding. - event_time (~.timestamp.Timestamp): - The time at which the event took place. For - example, if the finding represents an open - firewall it would capture the time the detector - believes the firewall became open. The accuracy - is determined by the detector. - create_time (~.timestamp.Timestamp): - The time at which the finding was created in - Security Command Center. - """ - - class State(proto.Enum): - r"""The state of the finding.""" - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - INACTIVE = 2 - - name = proto.Field(proto.STRING, number=1) - - parent = proto.Field(proto.STRING, number=2) - - resource_name = proto.Field(proto.STRING, number=3) - - state = proto.Field(proto.ENUM, number=4, enum=State,) - - category = proto.Field(proto.STRING, number=5) - - external_uri = proto.Field(proto.STRING, number=6) - - source_properties = proto.MapField( - proto.STRING, proto.MESSAGE, number=7, message=struct.Value, - ) - - security_marks = proto.Field( - proto.MESSAGE, number=8, message=gcs_security_marks.SecurityMarks, - ) - - event_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) - - create_time = proto.Field(proto.MESSAGE, number=10, message=timestamp.Timestamp,) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/notification_config.py b/google/cloud/securitycenter_v1/types/notification_config.py deleted file mode 100644 index 87e4d654..00000000 --- a/google/cloud/securitycenter_v1/types/notification_config.py +++ /dev/null @@ -1,100 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 proto # type: ignore - - -__protobuf__ = proto.module( - package="google.cloud.securitycenter.v1", manifest={"NotificationConfig",}, -) - - -class NotificationConfig(proto.Message): - r"""Cloud Security Command Center (Cloud SCC) notification - configs. - A notification config is a Cloud SCC resource that contains the - configuration to send notifications for create/update events of - findings, assets and etc. - - Attributes: - name (str): - The relative resource name of this notification config. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/notificationConfigs/notify_public_bucket". - description (str): - The description of the notification config - (max of 1024 characters). - pubsub_topic (str): - The PubSub topic to send notifications to. Its format is - "projects/[project_id]/topics/[topic]". - service_account (str): - Output only. The service account that needs - "pubsub.topics.publish" permission to publish to - the PubSub topic. - streaming_config (~.notification_config.NotificationConfig.StreamingConfig): - The config for triggering streaming-based - notifications. - """ - - class StreamingConfig(proto.Message): - r"""The config for streaming-based notifications, which send each - event as soon as it is detected. - - Attributes: - filter (str): - Expression that defines the filter to apply across - create/update events of assets or findings as specified by - the event type. The expression is a list of zero or more - restrictions combined via logical operators ``AND`` and - ``OR``. Parentheses are supported, and ``OR`` has higher - precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the - corresponding resource. - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - """ - - filter = proto.Field(proto.STRING, number=1) - - name = proto.Field(proto.STRING, number=1) - - description = proto.Field(proto.STRING, number=2) - - pubsub_topic = proto.Field(proto.STRING, number=3) - - service_account = proto.Field(proto.STRING, number=4) - - streaming_config = proto.Field( - proto.MESSAGE, number=5, oneof="notify_config", message=StreamingConfig, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/notification_message.py b/google/cloud/securitycenter_v1/types/notification_message.py deleted file mode 100644 index c836cad9..00000000 --- a/google/cloud/securitycenter_v1/types/notification_message.py +++ /dev/null @@ -1,54 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 proto # type: ignore - - -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import resource as gcs_resource - - -__protobuf__ = proto.module( - package="google.cloud.securitycenter.v1", manifest={"NotificationMessage",}, -) - - -class NotificationMessage(proto.Message): - r"""Cloud SCC's Notification - - Attributes: - notification_config_name (str): - Name of the notification config that - generated current notification. - finding (~.gcs_finding.Finding): - If it's a Finding based notification config, - this field will be populated. - resource (~.gcs_resource.Resource): - The Cloud resource tied to this - notification's Finding. - """ - - notification_config_name = proto.Field(proto.STRING, number=1) - - finding = proto.Field( - proto.MESSAGE, number=2, oneof="event", message=gcs_finding.Finding, - ) - - resource = proto.Field(proto.MESSAGE, number=3, message=gcs_resource.Resource,) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/organization_settings.py b/google/cloud/securitycenter_v1/types/organization_settings.py deleted file mode 100644 index ad4bc9f8..00000000 --- a/google/cloud/securitycenter_v1/types/organization_settings.py +++ /dev/null @@ -1,89 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 proto # type: ignore - - -__protobuf__ = proto.module( - package="google.cloud.securitycenter.v1", manifest={"OrganizationSettings",}, -) - - -class OrganizationSettings(proto.Message): - r"""User specified settings that are attached to the Security - Command Center organization. - - Attributes: - name (str): - The relative resource name of the settings. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/organizationSettings". - enable_asset_discovery (bool): - A flag that indicates if Asset Discovery should be enabled. - If the flag is set to ``true``, then discovery of assets - will occur. If it is set to \`false, all historical assets - will remain, but discovery of future assets will not occur. - asset_discovery_config (~.organization_settings.OrganizationSettings.AssetDiscoveryConfig): - The configuration used for Asset Discovery - runs. - """ - - class AssetDiscoveryConfig(proto.Message): - r"""The configuration used for Asset Discovery runs. - - Attributes: - project_ids (Sequence[str]): - The project ids to use for filtering asset - discovery. - inclusion_mode (~.organization_settings.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): - The mode to use for filtering asset - discovery. - """ - - class InclusionMode(proto.Enum): - r"""The mode of inclusion when running Asset Discovery. Asset discovery - can be limited by explicitly identifying projects to be included or - excluded. If INCLUDE_ONLY is set, then only those projects within - the organization and their children are discovered during asset - discovery. If EXCLUDE is set, then projects that don't match those - projects are discovered during asset discovery. If neither are set, - then all projects within the organization are discovered during - asset discovery. - """ - INCLUSION_MODE_UNSPECIFIED = 0 - INCLUDE_ONLY = 1 - EXCLUDE = 2 - - project_ids = proto.RepeatedField(proto.STRING, number=1) - - inclusion_mode = proto.Field( - proto.ENUM, - number=2, - enum="OrganizationSettings.AssetDiscoveryConfig.InclusionMode", - ) - - name = proto.Field(proto.STRING, number=1) - - enable_asset_discovery = proto.Field(proto.BOOL, number=2) - - asset_discovery_config = proto.Field( - proto.MESSAGE, number=3, message=AssetDiscoveryConfig, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/resource.py b/google/cloud/securitycenter_v1/types/resource.py deleted file mode 100644 index 49c709fa..00000000 --- a/google/cloud/securitycenter_v1/types/resource.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 proto # type: ignore - - -__protobuf__ = proto.module( - package="google.cloud.securitycenter.v1", manifest={"Resource",}, -) - - -class Resource(proto.Message): - r"""Information related to the Google Cloud resource. - - Attributes: - name (str): - The full resource name of the resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - project (str): - The full resource name of project that the - resource belongs to. - project_display_name (str): - The human readable name of project that the - resource belongs to. - parent (str): - The full resource name of resource's parent. - parent_display_name (str): - The human readable name of resource's parent. - """ - - name = proto.Field(proto.STRING, number=1) - - project = proto.Field(proto.STRING, number=2) - - project_display_name = proto.Field(proto.STRING, number=3) - - parent = proto.Field(proto.STRING, number=4) - - parent_display_name = proto.Field(proto.STRING, number=5) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py b/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py deleted file mode 100644 index eeed56ef..00000000 --- a/google/cloud/securitycenter_v1/types/run_asset_discovery_response.py +++ /dev/null @@ -1,52 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 proto # type: ignore - - -from google.protobuf import duration_pb2 as gp_duration # type: ignore - - -__protobuf__ = proto.module( - package="google.cloud.securitycenter.v1", manifest={"RunAssetDiscoveryResponse",}, -) - - -class RunAssetDiscoveryResponse(proto.Message): - r"""Response of asset discovery run - - Attributes: - state (~.run_asset_discovery_response.RunAssetDiscoveryResponse.State): - The state of an asset discovery run. - duration (~.gp_duration.Duration): - The duration between asset discovery run - start and end - """ - - class State(proto.Enum): - r"""The state of an asset discovery run.""" - STATE_UNSPECIFIED = 0 - COMPLETED = 1 - SUPERSEDED = 2 - TERMINATED = 3 - - state = proto.Field(proto.ENUM, number=1, enum=State,) - - duration = proto.Field(proto.MESSAGE, number=2, message=gp_duration.Duration,) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/security_marks.py b/google/cloud/securitycenter_v1/types/security_marks.py deleted file mode 100644 index 21bf0b0a..00000000 --- a/google/cloud/securitycenter_v1/types/security_marks.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 proto # type: ignore - - -__protobuf__ = proto.module( - package="google.cloud.securitycenter.v1", manifest={"SecurityMarks",}, -) - - -class SecurityMarks(proto.Message): - r"""User specified security marks that are attached to the parent - Security Command Center resource. Security marks are scoped - within a Security Command Center organization -- they can be - modified and viewed by all users who have proper permissions on - the organization. - - Attributes: - name (str): - The relative resource name of the SecurityMarks. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Examples: - "organizations/{organization_id}/assets/{asset_id}/securityMarks" - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks". - marks (Sequence[~.security_marks.SecurityMarks.MarksEntry]): - Mutable user specified security marks belonging to the - parent resource. Constraints are as follows: - - - Keys and values are treated as case insensitive - - Keys must be between 1 - 256 characters (inclusive) - - Keys must be letters, numbers, underscores, or dashes - - Values have leading and trailing whitespace trimmed, - remaining characters must be between 1 - 4096 characters - (inclusive) - """ - - name = proto.Field(proto.STRING, number=1) - - marks = proto.MapField(proto.STRING, proto.STRING, number=2) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/securitycenter_service.py b/google/cloud/securitycenter_v1/types/securitycenter_service.py deleted file mode 100644 index 1653a05b..00000000 --- a/google/cloud/securitycenter_v1/types/securitycenter_service.py +++ /dev/null @@ -1,1353 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 proto # type: ignore - - -from google.cloud.securitycenter_v1.types import asset as gcs_asset -from google.cloud.securitycenter_v1.types import finding as gcs_finding -from google.cloud.securitycenter_v1.types import ( - notification_config as gcs_notification_config, -) -from google.cloud.securitycenter_v1.types import ( - organization_settings as gcs_organization_settings, -) -from google.cloud.securitycenter_v1.types import security_marks as gcs_security_marks -from google.cloud.securitycenter_v1.types import source as gcs_source -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as gp_field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - - -__protobuf__ = proto.module( - package="google.cloud.securitycenter.v1", - manifest={ - "CreateFindingRequest", - "CreateNotificationConfigRequest", - "CreateSourceRequest", - "DeleteNotificationConfigRequest", - "GetNotificationConfigRequest", - "GetOrganizationSettingsRequest", - "GetSourceRequest", - "GroupAssetsRequest", - "GroupAssetsResponse", - "GroupFindingsRequest", - "GroupFindingsResponse", - "GroupResult", - "ListNotificationConfigsRequest", - "ListNotificationConfigsResponse", - "ListSourcesRequest", - "ListSourcesResponse", - "ListAssetsRequest", - "ListAssetsResponse", - "ListFindingsRequest", - "ListFindingsResponse", - "SetFindingStateRequest", - "RunAssetDiscoveryRequest", - "UpdateFindingRequest", - "UpdateNotificationConfigRequest", - "UpdateOrganizationSettingsRequest", - "UpdateSourceRequest", - "UpdateSecurityMarksRequest", - }, -) - - -class CreateFindingRequest(proto.Message): - r"""Request message for creating a finding. - - Attributes: - parent (str): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - finding_id (str): - Required. Unique identifier provided by the - client within the parent scope. It must be - alphanumeric and less than or equal to 32 - characters and greater than 0 characters in - length. - finding (~.gcs_finding.Finding): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output only - fields on this resource. - """ - - parent = proto.Field(proto.STRING, number=1) - - finding_id = proto.Field(proto.STRING, number=2) - - finding = proto.Field(proto.MESSAGE, number=3, message=gcs_finding.Finding,) - - -class CreateNotificationConfigRequest(proto.Message): - r"""Request message for creating a notification config. - - Attributes: - parent (str): - Required. Resource name of the new notification config's - parent. Its format is "organizations/[organization_id]". - config_id (str): - Required. - Unique identifier provided by the client within - the parent scope. It must be between 1 and 128 - characters, and contains alphanumeric - characters, underscores or hyphens only. - notification_config (~.gcs_notification_config.NotificationConfig): - Required. The notification config being - created. The name and the service account will - be ignored as they are both output only fields - on this resource. - """ - - parent = proto.Field(proto.STRING, number=1) - - config_id = proto.Field(proto.STRING, number=2) - - notification_config = proto.Field( - proto.MESSAGE, number=3, message=gcs_notification_config.NotificationConfig, - ) - - -class CreateSourceRequest(proto.Message): - r"""Request message for creating a source. - - Attributes: - parent (str): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - source (~.gcs_source.Source): - Required. The Source being created, only the display_name - and description will be used. All other fields will be - ignored. - """ - - parent = proto.Field(proto.STRING, number=1) - - source = proto.Field(proto.MESSAGE, number=2, message=gcs_source.Source,) - - -class DeleteNotificationConfigRequest(proto.Message): - r"""Request message for deleting a notification config. - - Attributes: - name (str): - Required. Name of the notification config to delete. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_id]". - """ - - name = proto.Field(proto.STRING, number=1) - - -class GetNotificationConfigRequest(proto.Message): - r"""Request message for getting a notification config. - - Attributes: - name (str): - Required. Name of the notification config to get. Its format - is - "organizations/[organization_id]/notificationConfigs/[config_id]". - """ - - name = proto.Field(proto.STRING, number=1) - - -class GetOrganizationSettingsRequest(proto.Message): - r"""Request message for getting organization settings. - - Attributes: - name (str): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - """ - - name = proto.Field(proto.STRING, number=1) - - -class GetSourceRequest(proto.Message): - r"""Request message for getting a source. - - Attributes: - name (str): - Required. Relative resource name of the source. Its format - is "organizations/[organization_id]/source/[source_id]". - """ - - name = proto.Field(proto.STRING, number=1) - - -class GroupAssetsRequest(proto.Message): - r"""Request message for grouping by assets. - - Attributes: - parent (str): - Required. Name of the organization to groupBy. Its format is - "organizations/[organization_id]". - filter (str): - Expression that defines the filter to apply across assets. - The expression is a list of zero or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the Asset - resource. Examples include: - - - name - - security_center_properties.resource_name - - resource_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``update_time = "2019-06-10T16:07:18-07:00"`` - ``update_time = 1560208038000`` - - - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``create_time = "2019-06-10T16:07:18-07:00"`` - ``create_time = 1560208038000`` - - - iam_policy.policy_blob: ``=``, ``:`` - - - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, - ``<=`` - - - security_marks.marks: ``=``, ``:`` - - - security_center_properties.resource_name: ``=``, ``:`` - - - security_center_properties.resource_display_name: ``=``, - ``:`` - - - security_center_properties.resource_type: ``=``, ``:`` - - - security_center_properties.resource_parent: ``=``, ``:`` - - - security_center_properties.resource_parent_display_name: - ``=``, ``:`` - - - security_center_properties.resource_project: ``=``, ``:`` - - - security_center_properties.resource_project_display_name: - ``=``, ``:`` - - - security_center_properties.resource_owners: ``=``, ``:`` - - For example, ``resource_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based on a - property existing:\ ``resource_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-resource_properties.my_property : ""`` - group_by (str): - Required. Expression that defines what assets fields to use - for grouping. The string value should follow SQL syntax: - comma separated list of fields. For example: - "security_center_properties.resource_project,security_center_properties.project". - - The following fields are supported when compare_duration is - not set: - - - security_center_properties.resource_project - - security_center_properties.resource_project_display_name - - security_center_properties.resource_type - - security_center_properties.resource_parent - - security_center_properties.resource_parent_display_name - - The following fields are supported when compare_duration is - set: - - - security_center_properties.resource_type - - security_center_properties.resource_project_display_name - - security_center_properties.resource_parent_display_name - compare_duration (~.duration.Duration): - When compare_duration is set, the GroupResult's - "state_change" property is updated to indicate whether the - asset was added, removed, or remained present during the - compare_duration period of time that precedes the read_time. - This is the time between (read_time - compare_duration) and - read_time. - - The state change value is derived based on the presence of - the asset at the two points in time. Intermediate state - changes between the two times don't affect the result. For - example, the results aren't affected if the asset is removed - and re-created again. - - Possible "state_change" values when compare_duration is - specified: - - - "ADDED": indicates that the asset was not present at the - start of compare_duration, but present at reference_time. - - "REMOVED": indicates that the asset was present at the - start of compare_duration, but not present at - reference_time. - - "ACTIVE": indicates that the asset was present at both - the start and the end of the time period defined by - compare_duration and reference_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all assets present at read_time. - - If this field is set then ``state_change`` must be a - specified field in ``group_by``. - read_time (~.timestamp.Timestamp): - Time used as a reference point when filtering - assets. The filter is limited to assets existing - at the supplied time and their values are those - at that specific time. Absence of this field - will default to the API's version of NOW. - page_token (str): - The value returned by the last ``GroupAssetsResponse``; - indicates that this is a continuation of a prior - ``GroupAssets`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - group_by = proto.Field(proto.STRING, number=3) - - compare_duration = proto.Field(proto.MESSAGE, number=4, message=duration.Duration,) - - read_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) - - page_token = proto.Field(proto.STRING, number=7) - - page_size = proto.Field(proto.INT32, number=8) - - -class GroupAssetsResponse(proto.Message): - r"""Response message for grouping by assets. - - Attributes: - group_by_results (Sequence[~.securitycenter_service.GroupResult]): - Group results. There exists an element for - each existing unique combination of - property/values. The element contains a count - for the number of times those specific - property/values appear. - read_time (~.timestamp.Timestamp): - Time used for executing the groupBy request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of results matching the - query. - """ - - @property - def raw_page(self): - return self - - group_by_results = proto.RepeatedField( - proto.MESSAGE, number=1, message="GroupResult", - ) - - read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - next_page_token = proto.Field(proto.STRING, number=3) - - total_size = proto.Field(proto.INT32, number=4) - - -class GroupFindingsRequest(proto.Message): - r"""Request message for grouping by findings. - - Attributes: - parent (str): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]". To - groupBy across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/- - filter (str): - Expression that defines the filter to apply across findings. - The expression is a list of one or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. Examples include: - - - name - - source_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - parent: ``=``, ``:`` - - - resource_name: ``=``, ``:`` - - - state: ``=``, ``:`` - - - category: ``=``, ``:`` - - - external_uri: ``=``, ``:`` - - - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``event_time = "2019-06-10T16:07:18-07:00"`` - ``event_time = 1560208038000`` - - - security_marks.marks: ``=``, ``:`` - - - source_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, - ``<=`` - - For example, ``source_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based on a - property existing: ``source_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-source_properties.my_property : ""`` - group_by (str): - Required. Expression that defines what assets fields to use - for grouping (including ``state_change``). The string value - should follow SQL syntax: comma separated list of fields. - For example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - - The following fields are supported when compare_duration is - set: - - - state_change - read_time (~.timestamp.Timestamp): - Time used as a reference point when filtering - findings. The filter is limited to findings - existing at the supplied time and their values - are those at that specific time. Absence of this - field will default to the API's version of NOW. - compare_duration (~.duration.Duration): - When compare_duration is set, the GroupResult's - "state_change" attribute is updated to indicate whether the - finding had its state changed, the finding's state remained - unchanged, or if the finding was added during the - compare_duration period of time that precedes the read_time. - This is the time between (read_time - compare_duration) and - read_time. - - The state_change value is derived based on the presence and - state of the finding at the two points in time. Intermediate - state changes between the two times don't affect the result. - For example, the results aren't affected if the finding is - made inactive and then active again. - - Possible "state_change" values when compare_duration is - specified: - - - "CHANGED": indicates that the finding was present and - matched the given filter at the start of - compare_duration, but changed its state at read_time. - - "UNCHANGED": indicates that the finding was present and - matched the given filter at the start of compare_duration - and did not change state at read_time. - - "ADDED": indicates that the finding did not match the - given filter or was not present at the start of - compare_duration, but was present at read_time. - - "REMOVED": indicates that the finding was present and - matched the filter at the start of compare_duration, but - did not match the filter at read_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all findings present at read_time. - - If this field is set then ``state_change`` must be a - specified field in ``group_by``. - page_token (str): - The value returned by the last ``GroupFindingsResponse``; - indicates that this is a continuation of a prior - ``GroupFindings`` call, and that the system should return - the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - group_by = proto.Field(proto.STRING, number=3) - - read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) - - compare_duration = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) - - page_token = proto.Field(proto.STRING, number=7) - - page_size = proto.Field(proto.INT32, number=8) - - -class GroupFindingsResponse(proto.Message): - r"""Response message for group by findings. - - Attributes: - group_by_results (Sequence[~.securitycenter_service.GroupResult]): - Group results. There exists an element for - each existing unique combination of - property/values. The element contains a count - for the number of times those specific - property/values appear. - read_time (~.timestamp.Timestamp): - Time used for executing the groupBy request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of results matching the - query. - """ - - @property - def raw_page(self): - return self - - group_by_results = proto.RepeatedField( - proto.MESSAGE, number=1, message="GroupResult", - ) - - read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - next_page_token = proto.Field(proto.STRING, number=3) - - total_size = proto.Field(proto.INT32, number=4) - - -class GroupResult(proto.Message): - r"""Result containing the properties and count of a groupBy - request. - - Attributes: - properties (Sequence[~.securitycenter_service.GroupResult.PropertiesEntry]): - Properties matching the groupBy fields in the - request. - count (int): - Total count of resources for the given - properties. - """ - - properties = proto.MapField( - proto.STRING, proto.MESSAGE, number=1, message=struct.Value, - ) - - count = proto.Field(proto.INT64, number=2) - - -class ListNotificationConfigsRequest(proto.Message): - r"""Request message for listing notification configs. - - Attributes: - parent (str): - Required. Name of the organization to list notification - configs. Its format is "organizations/[organization_id]". - page_token (str): - The value returned by the last - ``ListNotificationConfigsResponse``; indicates that this is - a continuation of a prior ``ListNotificationConfigs`` call, - and that the system should return the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field(proto.STRING, number=1) - - page_token = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=3) - - -class ListNotificationConfigsResponse(proto.Message): - r"""Response message for listing notification configs. - - Attributes: - notification_configs (Sequence[~.gcs_notification_config.NotificationConfig]): - Notification configs belonging to the - requested parent. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - notification_configs = proto.RepeatedField( - proto.MESSAGE, number=1, message=gcs_notification_config.NotificationConfig, - ) - - next_page_token = proto.Field(proto.STRING, number=2) - - -class ListSourcesRequest(proto.Message): - r"""Request message for listing sources. - - Attributes: - parent (str): - Required. Resource name of the parent of sources to list. - Its format should be "organizations/[organization_id]". - page_token (str): - The value returned by the last ``ListSourcesResponse``; - indicates that this is a continuation of a prior - ``ListSources`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field(proto.STRING, number=1) - - page_token = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=7) - - -class ListSourcesResponse(proto.Message): - r"""Response message for listing sources. - - Attributes: - sources (Sequence[~.gcs_source.Source]): - Sources belonging to the requested parent. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - sources = proto.RepeatedField(proto.MESSAGE, number=1, message=gcs_source.Source,) - - next_page_token = proto.Field(proto.STRING, number=2) - - -class ListAssetsRequest(proto.Message): - r"""Request message for listing assets. - - Attributes: - parent (str): - Required. Name of the organization assets should belong to. - Its format is "organizations/[organization_id]". - filter (str): - Expression that defines the filter to apply across assets. - The expression is a list of zero or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the Asset - resource. Examples include: - - - name - - security_center_properties.resource_name - - resource_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following are the allowed field and operator - combinations: - - - name: ``=`` - - - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``update_time = "2019-06-10T16:07:18-07:00"`` - ``update_time = 1560208038000`` - - - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``create_time = "2019-06-10T16:07:18-07:00"`` - ``create_time = 1560208038000`` - - - iam_policy.policy_blob: ``=``, ``:`` - - - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, - ``<=`` - - - security_marks.marks: ``=``, ``:`` - - - security_center_properties.resource_name: ``=``, ``:`` - - - security_center_properties.resource_display_name: ``=``, - ``:`` - - - security_center_properties.resource_type: ``=``, ``:`` - - - security_center_properties.resource_parent: ``=``, ``:`` - - - security_center_properties.resource_parent_display_name: - ``=``, ``:`` - - - security_center_properties.resource_project: ``=``, ``:`` - - - security_center_properties.resource_project_display_name: - ``=``, ``:`` - - - security_center_properties.resource_owners: ``=``, ``:`` - - For example, ``resource_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based on a - property existing: ``resource_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-resource_properties.my_property : ""`` - order_by (str): - Expression that defines what fields and order to use for - sorting. The string value should follow SQL syntax: comma - separated list of fields. For example: - "name,resource_properties.a_property". The default sorting - order is ascending. To specify descending order for a field, - a suffix " desc" should be appended to the field name. For - example: "name desc,resource_properties.a_property". - Redundant space characters in the syntax are insignificant. - "name desc,resource_properties.a_property" and " name desc , - resource_properties.a_property " are equivalent. - - The following fields are supported: name update_time - resource_properties security_marks.marks - security_center_properties.resource_name - security_center_properties.resource_display_name - security_center_properties.resource_parent - security_center_properties.resource_parent_display_name - security_center_properties.resource_project - security_center_properties.resource_project_display_name - security_center_properties.resource_type - read_time (~.timestamp.Timestamp): - Time used as a reference point when filtering - assets. The filter is limited to assets existing - at the supplied time and their values are those - at that specific time. Absence of this field - will default to the API's version of NOW. - compare_duration (~.duration.Duration): - When compare_duration is set, the ListAssetsResult's - "state_change" attribute is updated to indicate whether the - asset was added, removed, or remained present during the - compare_duration period of time that precedes the read_time. - This is the time between (read_time - compare_duration) and - read_time. - - The state_change value is derived based on the presence of - the asset at the two points in time. Intermediate state - changes between the two times don't affect the result. For - example, the results aren't affected if the asset is removed - and re-created again. - - Possible "state_change" values when compare_duration is - specified: - - - "ADDED": indicates that the asset was not present at the - start of compare_duration, but present at read_time. - - "REMOVED": indicates that the asset was present at the - start of compare_duration, but not present at read_time. - - "ACTIVE": indicates that the asset was present at both - the start and the end of the time period defined by - compare_duration and read_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all assets present at read_time. - field_mask (~.gp_field_mask.FieldMask): - Optional. A field mask to specify the - ListAssetsResult fields to be listed in the - response. An empty field mask will list all - fields. - page_token (str): - The value returned by the last ``ListAssetsResponse``; - indicates that this is a continuation of a prior - ``ListAssets`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - order_by = proto.Field(proto.STRING, number=3) - - read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) - - compare_duration = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) - - field_mask = proto.Field(proto.MESSAGE, number=7, message=gp_field_mask.FieldMask,) - - page_token = proto.Field(proto.STRING, number=8) - - page_size = proto.Field(proto.INT32, number=9) - - -class ListAssetsResponse(proto.Message): - r"""Response message for listing assets. - - Attributes: - list_assets_results (Sequence[~.securitycenter_service.ListAssetsResponse.ListAssetsResult]): - Assets matching the list request. - read_time (~.timestamp.Timestamp): - Time used for executing the list request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of assets matching the - query. - """ - - class ListAssetsResult(proto.Message): - r"""Result containing the Asset and its State. - - Attributes: - asset (~.gcs_asset.Asset): - Asset matching the search request. - state_change (~.securitycenter_service.ListAssetsResponse.ListAssetsResult.StateChange): - State change of the asset between the points - in time. - """ - - class StateChange(proto.Enum): - r"""The change in state of the asset. - - When querying across two points in time this describes the change - between the two points: ADDED, REMOVED, or ACTIVE. If there was no - compare_duration supplied in the request the state change will be: - UNUSED - """ - UNUSED = 0 - ADDED = 1 - REMOVED = 2 - ACTIVE = 3 - - asset = proto.Field(proto.MESSAGE, number=1, message=gcs_asset.Asset,) - - state_change = proto.Field( - proto.ENUM, - number=2, - enum="ListAssetsResponse.ListAssetsResult.StateChange", - ) - - @property - def raw_page(self): - return self - - list_assets_results = proto.RepeatedField( - proto.MESSAGE, number=1, message=ListAssetsResult, - ) - - read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - next_page_token = proto.Field(proto.STRING, number=3) - - total_size = proto.Field(proto.INT32, number=4) - - -class ListFindingsRequest(proto.Message): - r"""Request message for listing findings. - - Attributes: - parent (str): - Required. Name of the source the findings belong to. Its - format is - "organizations/[organization_id]/sources/[source_id]". To - list across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/- - filter (str): - Expression that defines the filter to apply across findings. - The expression is a list of one or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. Examples include: - - - name - - source_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - name: ``=`` parent: ``=``, ``:`` resource_name: ``=``, ``:`` - state: ``=``, ``:`` category: ``=``, ``:`` external_uri: - ``=``, ``:`` event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an RFC3339 - string. Examples: - ``event_time = "2019-06-10T16:07:18-07:00"`` - ``event_time = 1560208038000`` - - security_marks.marks: ``=``, ``:`` source_properties: ``=``, - ``:``, ``>``, ``<``, ``>=``, ``<=`` - - For example, ``source_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based on a - property existing: ``source_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-source_properties.my_property : ""`` - order_by (str): - Expression that defines what fields and order to use for - sorting. The string value should follow SQL syntax: comma - separated list of fields. For example: - "name,resource_properties.a_property". The default sorting - order is ascending. To specify descending order for a field, - a suffix " desc" should be appended to the field name. For - example: "name desc,source_properties.a_property". Redundant - space characters in the syntax are insignificant. "name - desc,source_properties.a_property" and " name desc , - source_properties.a_property " are equivalent. - - The following fields are supported: name parent state - category resource_name event_time source_properties - security_marks.marks - read_time (~.timestamp.Timestamp): - Time used as a reference point when filtering - findings. The filter is limited to findings - existing at the supplied time and their values - are those at that specific time. Absence of this - field will default to the API's version of NOW. - compare_duration (~.duration.Duration): - When compare_duration is set, the ListFindingsResult's - "state_change" attribute is updated to indicate whether the - finding had its state changed, the finding's state remained - unchanged, or if the finding was added in any state during - the compare_duration period of time that precedes the - read_time. This is the time between (read_time - - compare_duration) and read_time. - - The state_change value is derived based on the presence and - state of the finding at the two points in time. Intermediate - state changes between the two times don't affect the result. - For example, the results aren't affected if the finding is - made inactive and then active again. - - Possible "state_change" values when compare_duration is - specified: - - - "CHANGED": indicates that the finding was present and - matched the given filter at the start of - compare_duration, but changed its state at read_time. - - "UNCHANGED": indicates that the finding was present and - matched the given filter at the start of compare_duration - and did not change state at read_time. - - "ADDED": indicates that the finding did not match the - given filter or was not present at the start of - compare_duration, but was present at read_time. - - "REMOVED": indicates that the finding was present and - matched the filter at the start of compare_duration, but - did not match the filter at read_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all findings present at read_time. - field_mask (~.gp_field_mask.FieldMask): - Optional. A field mask to specify the Finding - fields to be listed in the response. An empty - field mask will list all fields. - page_token (str): - The value returned by the last ``ListFindingsResponse``; - indicates that this is a continuation of a prior - ``ListFindings`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - order_by = proto.Field(proto.STRING, number=3) - - read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) - - compare_duration = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) - - field_mask = proto.Field(proto.MESSAGE, number=7, message=gp_field_mask.FieldMask,) - - page_token = proto.Field(proto.STRING, number=8) - - page_size = proto.Field(proto.INT32, number=9) - - -class ListFindingsResponse(proto.Message): - r"""Response message for listing findings. - - Attributes: - list_findings_results (Sequence[~.securitycenter_service.ListFindingsResponse.ListFindingsResult]): - Findings matching the list request. - read_time (~.timestamp.Timestamp): - Time used for executing the list request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of findings matching the - query. - """ - - class ListFindingsResult(proto.Message): - r"""Result containing the Finding and its StateChange. - - Attributes: - finding (~.gcs_finding.Finding): - Finding matching the search request. - state_change (~.securitycenter_service.ListFindingsResponse.ListFindingsResult.StateChange): - State change of the finding between the - points in time. - resource (~.securitycenter_service.ListFindingsResponse.ListFindingsResult.Resource): - Output only. Resource that is associated with - this finding. - """ - - class StateChange(proto.Enum): - r"""The change in state of the finding. - - When querying across two points in time this describes the change in - the finding between the two points: CHANGED, UNCHANGED, ADDED, or - REMOVED. Findings can not be deleted, so REMOVED implies that the - finding at timestamp does not match the filter specified, but it did - at timestamp - compare_duration. If there was no compare_duration - supplied in the request the state change will be: UNUSED - """ - UNUSED = 0 - CHANGED = 1 - UNCHANGED = 2 - ADDED = 3 - REMOVED = 4 - - class Resource(proto.Message): - r"""Information related to the Google Cloud resource that is - associated with this finding. - - Attributes: - name (str): - The full resource name of the resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - project_name (str): - The full resource name of project that the - resource belongs to. - project_display_name (str): - The human readable name of project that the - resource belongs to. - parent_name (str): - The full resource name of resource's parent. - parent_display_name (str): - The human readable name of resource's parent. - """ - - name = proto.Field(proto.STRING, number=1) - - project_name = proto.Field(proto.STRING, number=2) - - project_display_name = proto.Field(proto.STRING, number=3) - - parent_name = proto.Field(proto.STRING, number=4) - - parent_display_name = proto.Field(proto.STRING, number=5) - - finding = proto.Field(proto.MESSAGE, number=1, message=gcs_finding.Finding,) - - state_change = proto.Field( - proto.ENUM, - number=2, - enum="ListFindingsResponse.ListFindingsResult.StateChange", - ) - - resource = proto.Field( - proto.MESSAGE, - number=3, - message="ListFindingsResponse.ListFindingsResult.Resource", - ) - - @property - def raw_page(self): - return self - - list_findings_results = proto.RepeatedField( - proto.MESSAGE, number=1, message=ListFindingsResult, - ) - - read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - next_page_token = proto.Field(proto.STRING, number=3) - - total_size = proto.Field(proto.INT32, number=4) - - -class SetFindingStateRequest(proto.Message): - r"""Request message for updating a finding's state. - - Attributes: - name (str): - Required. The relative resource name of the finding. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - state (~.gcs_finding.Finding.State): - Required. The desired State of the finding. - start_time (~.timestamp.Timestamp): - Required. The time at which the updated state - takes effect. - """ - - name = proto.Field(proto.STRING, number=1) - - state = proto.Field(proto.ENUM, number=2, enum=gcs_finding.Finding.State,) - - start_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) - - -class RunAssetDiscoveryRequest(proto.Message): - r"""Request message for running asset discovery for an - organization. - - Attributes: - parent (str): - Required. Name of the organization to run asset discovery - for. Its format is "organizations/[organization_id]". - """ - - parent = proto.Field(proto.STRING, number=1) - - -class UpdateFindingRequest(proto.Message): - r"""Request message for updating or creating a finding. - - Attributes: - finding (~.gcs_finding.Finding): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the name - must be alphanumeric and less than or equal to 32 characters - and greater than 0 characters in length. - update_mask (~.gp_field_mask.FieldMask): - The FieldMask to use when updating the finding resource. - This field should not be specified when creating a finding. - - When updating a finding, an empty mask is treated as - updating all mutable fields and replacing source_properties. - Individual source_properties can be added/updated by using - "source_properties." in the field mask. - """ - - finding = proto.Field(proto.MESSAGE, number=1, message=gcs_finding.Finding,) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) - - -class UpdateNotificationConfigRequest(proto.Message): - r"""Request message for updating a notification config. - - Attributes: - notification_config (~.gcs_notification_config.NotificationConfig): - Required. The notification config to update. - update_mask (~.gp_field_mask.FieldMask): - The FieldMask to use when updating the - notification config. - If empty all mutable fields will be updated. - """ - - notification_config = proto.Field( - proto.MESSAGE, number=1, message=gcs_notification_config.NotificationConfig, - ) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) - - -class UpdateOrganizationSettingsRequest(proto.Message): - r"""Request message for updating an organization's settings. - - Attributes: - organization_settings (~.gcs_organization_settings.OrganizationSettings): - Required. The organization settings resource - to update. - update_mask (~.gp_field_mask.FieldMask): - The FieldMask to use when updating the - settings resource. - If empty all mutable fields will be updated. - """ - - organization_settings = proto.Field( - proto.MESSAGE, number=1, message=gcs_organization_settings.OrganizationSettings, - ) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) - - -class UpdateSourceRequest(proto.Message): - r"""Request message for updating a source. - - Attributes: - source (~.gcs_source.Source): - Required. The source resource to update. - update_mask (~.gp_field_mask.FieldMask): - The FieldMask to use when updating the source - resource. - If empty all mutable fields will be updated. - """ - - source = proto.Field(proto.MESSAGE, number=1, message=gcs_source.Source,) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) - - -class UpdateSecurityMarksRequest(proto.Message): - r"""Request message for updating a SecurityMarks resource. - - Attributes: - security_marks (~.gcs_security_marks.SecurityMarks): - Required. The security marks resource to - update. - update_mask (~.gp_field_mask.FieldMask): - The FieldMask to use when updating the security marks - resource. - - The field mask must not contain duplicate fields. If empty - or set to "marks", all marks will be replaced. Individual - marks can be updated using "marks.". - start_time (~.timestamp.Timestamp): - The time at which the updated SecurityMarks - take effect. If not set uses current server - time. Updates will be applied to the - SecurityMarks that are active immediately - preceding this time. - """ - - security_marks = proto.Field( - proto.MESSAGE, number=1, message=gcs_security_marks.SecurityMarks, - ) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) - - start_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1/types/source.py b/google/cloud/securitycenter_v1/types/source.py deleted file mode 100644 index ce412d1c..00000000 --- a/google/cloud/securitycenter_v1/types/source.py +++ /dev/null @@ -1,64 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 proto # type: ignore - - -__protobuf__ = proto.module( - package="google.cloud.securitycenter.v1", manifest={"Source",}, -) - - -class Source(proto.Message): - r"""Security Command Center finding source. A finding source - is an entity or a mechanism that can produce a finding. A source - is like a container of findings that come from the same scanner, - logger, monitor, and other tools. - - Attributes: - name (str): - The relative resource name of this source. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}". - display_name (str): - The source's display name. - A source's display name must be unique amongst - its siblings, for example, two sources with the - same parent can't share the same display name. - The display name must have a length between 1 - and 64 characters (inclusive). - description (str): - The description of the source (max of 1024 - characters). Example: - "Web Security Scanner is a web security scanner - for common vulnerabilities in App Engine - applications. It can automatically scan and - detect four common vulnerabilities, including - cross-site-scripting (XSS), Flash injection, - mixed content (HTTP in HTTPS), and outdated or - insecure libraries.". - """ - - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - description = proto.Field(proto.STRING, number=3) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1beta1/py.typed b/google/cloud/securitycenter_v1beta1/py.typed deleted file mode 100644 index 23a44fc7..00000000 --- a/google/cloud/securitycenter_v1beta1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-securitycenter package uses inline types. diff --git a/google/cloud/securitycenter_v1beta1/services/__init__.py b/google/cloud/securitycenter_v1beta1/services/__init__.py deleted file mode 100644 index 42ffdf2b..00000000 --- a/google/cloud/securitycenter_v1beta1/services/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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. -# diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/__init__.py b/google/cloud/securitycenter_v1beta1/services/security_center/__init__.py deleted file mode 100644 index 6250349b..00000000 --- a/google/cloud/securitycenter_v1beta1/services/security_center/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 SecurityCenterClient -from .async_client import SecurityCenterAsyncClient - -__all__ = ( - "SecurityCenterClient", - "SecurityCenterAsyncClient", -) diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py b/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py deleted file mode 100644 index 2be877e7..00000000 --- a/google/cloud/securitycenter_v1beta1/services/security_center/async_client.py +++ /dev/null @@ -1,1801 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation -from google.api_core import operation_async -from google.cloud.securitycenter_v1beta1.services.security_center import pagers -from google.cloud.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import organization_settings -from google.cloud.securitycenter_v1beta1.types import ( - organization_settings as gcs_organization_settings, -) -from google.cloud.securitycenter_v1beta1.types import security_marks -from google.cloud.securitycenter_v1beta1.types import ( - security_marks as gcs_security_marks, -) -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - -from .transports.base import SecurityCenterTransport -from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .client import SecurityCenterClient - - -class SecurityCenterAsyncClient: - """V1 Beta APIs for Security Center service.""" - - _client: SecurityCenterClient - - DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - - organization_settings_path = staticmethod( - SecurityCenterClient.organization_settings_path - ) - - finding_path = staticmethod(SecurityCenterClient.finding_path) - - source_path = staticmethod(SecurityCenterClient.source_path) - - security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) - - from_service_account_file = SecurityCenterClient.from_service_account_file - from_service_account_json = from_service_account_file - - get_transport_class = functools.partial( - type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient) - ) - - def __init__( - self, - *, - credentials: credentials.Credentials = None, - transport: Union[str, SecurityCenterTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - ) -> None: - """Instantiate the security center 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. - transport (Union[str, ~.SecurityCenterTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint, this is the default value for - the environment variable) and "auto" (auto switch to the default - mTLS endpoint if client SSL credentials is present). However, - the ``api_endpoint`` property takes precedence if provided. - (2) The ``client_cert_source`` property is used to provide client - SSL credentials for mutual TLS transport. If not provided, the - default SSL credentials will be used if present. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - - self._client = SecurityCenterClient( - credentials=credentials, transport=transport, client_options=client_options, - ) - - async def create_source( - self, - request: securitycenter_service.CreateSourceRequest = None, - *, - parent: str = None, - source: gcs_source.Source = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Creates a source. - - Args: - request (:class:`~.securitycenter_service.CreateSourceRequest`): - The request object. Request message for creating a - source. - parent (:class:`str`): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (:class:`~.gcs_source.Source`): - Required. The Source being created, only the - display_name and description will be used. All other - fields will be ignored. - This corresponds to the ``source`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([parent, source]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.CreateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_source, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def create_finding( - self, - request: securitycenter_service.CreateFindingRequest = None, - *, - parent: str = None, - finding_id: str = None, - finding: gcs_finding.Finding = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Args: - request (:class:`~.securitycenter_service.CreateFindingRequest`): - The request object. Request message for creating a - finding. - parent (:class:`str`): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding_id (:class:`str`): - Required. Unique identifier provided - by the client within the parent scope. - It must be alphanumeric and less than or - equal to 32 characters and greater than - 0 characters in length. - This corresponds to the ``finding_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding (:class:`~.gcs_finding.Finding`): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output - only fields on this resource. - This corresponds to the ``finding`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_finding.Finding: - Security Command Center finding. - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([parent, finding_id, finding]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.CreateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if finding_id is not None: - request.finding_id = finding_id - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_finding, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_iam_policy( - self, - request: iam_policy.GetIamPolicyRequest = None, - *, - resource: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: - r"""Gets the access control policy on the specified - Source. - - Args: - request (:class:`~.iam_policy.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - This corresponds to the ``resource`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([resource]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.GetIamPolicyRequest(**request) - - elif not request: - request = iam_policy.GetIamPolicyRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_iam_policy, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_organization_settings( - self, - request: securitycenter_service.GetOrganizationSettingsRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> organization_settings.OrganizationSettings: - r"""Gets the settings for an organization. - - Args: - request (:class:`~.securitycenter_service.GetOrganizationSettingsRequest`): - The request object. Request message for getting - organization settings. - name (:class:`str`): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - This corresponds to the ``name`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.organization_settings.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([name]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.GetOrganizationSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_organization_settings, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_source( - self, - request: securitycenter_service.GetSourceRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> source.Source: - r"""Gets a source. - - Args: - request (:class:`~.securitycenter_service.GetSourceRequest`): - The request object. Request message for getting a - source. - name (:class:`str`): - Required. Relative resource name of the source. Its - format is - "organizations/[organization_id]/source/[source_id]". - This corresponds to the ``name`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([name]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.GetSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_source, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def group_assets( - self, - request: securitycenter_service.GroupAssetsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupAssetsAsyncPager: - r"""Filters an organization's assets and groups them by - their specified properties. - - Args: - request (:class:`~.securitycenter_service.GroupAssetsRequest`): - The request object. Request message for grouping by - assets. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.GroupAssetsAsyncPager: - Response message for grouping by - assets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - - request = securitycenter_service.GroupAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.group_assets, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.GroupAssetsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - async def group_findings( - self, - request: securitycenter_service.GroupFindingsRequest = None, - *, - parent: str = None, - group_by: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupFindingsAsyncPager: - r"""Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - Args: - request (:class:`~.securitycenter_service.GroupFindingsRequest`): - The request object. Request message for grouping by - findings. - parent (:class:`str`): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]". - To groupBy across all sources provide a source_id of - ``-``. For example: - organizations/{organization_id}/sources/- - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - group_by (:class:`str`): - Required. Expression that defines what assets fields to - use for grouping (including ``state``). The string value - should follow SQL syntax: comma separated list of - fields. For example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - This corresponds to the ``group_by`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.GroupFindingsAsyncPager: - Response message for group by - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([parent, group_by]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.GroupFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.group_findings, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.GroupFindingsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_assets( - self, - request: securitycenter_service.ListAssetsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAssetsAsyncPager: - r"""Lists an organization's assets. - - Args: - request (:class:`~.securitycenter_service.ListAssetsRequest`): - The request object. Request message for listing assets. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.ListAssetsAsyncPager: - Response message for listing assets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - - request = securitycenter_service.ListAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_assets, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListAssetsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_findings( - self, - request: securitycenter_service.ListFindingsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFindingsAsyncPager: - r"""Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - Args: - request (:class:`~.securitycenter_service.ListFindingsRequest`): - The request object. Request message for listing - findings. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.ListFindingsAsyncPager: - Response message for listing - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - - request = securitycenter_service.ListFindingsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_findings, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListFindingsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_sources( - self, - request: securitycenter_service.ListSourcesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSourcesAsyncPager: - r"""Lists all sources belonging to an organization. - - Args: - request (:class:`~.securitycenter_service.ListSourcesRequest`): - The request object. Request message for listing sources. - parent (:class:`str`): - Required. Resource name of the parent of sources to - list. Its format should be - "organizations/[organization_id]". - This corresponds to the ``parent`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.ListSourcesAsyncPager: - Response message for listing sources. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.ListSourcesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_sources, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListSourcesAsyncPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - async def run_asset_discovery( - self, - request: securitycenter_service.RunAssetDiscoveryRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Args: - request (:class:`~.securitycenter_service.RunAssetDiscoveryRequest`): - The request object. Request message for running asset - discovery for an organization. - parent (:class:`str`): - Required. Name of the organization to run asset - discovery for. Its format is - "organizations/[organization_id]". - This corresponds to the ``parent`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:``~.empty.Empty``: A generic empty message that - you can re-use to avoid defining duplicated empty - messages in your APIs. A typical example is to use it as - the request or the response type of an API method. For - instance: - - :: - - service Foo { - rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); - } - - The JSON representation for ``Empty`` is empty JSON - object ``{}``. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.RunAssetDiscoveryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.run_asset_discovery, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - empty.Empty, - metadata_type=empty.Empty, - ) - - # Done; return the response. - return response - - async def set_finding_state( - self, - request: securitycenter_service.SetFindingStateRequest = None, - *, - name: str = None, - state: finding.Finding.State = None, - start_time: timestamp.Timestamp = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the state of a finding. - - Args: - request (:class:`~.securitycenter_service.SetFindingStateRequest`): - The request object. Request message for updating a - finding's state. - name (:class:`str`): - Required. The relative resource name of the finding. - See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - state (:class:`~.finding.Finding.State`): - Required. The desired State of the - finding. - This corresponds to the ``state`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - start_time (:class:`~.timestamp.Timestamp`): - Required. The time at which the - updated state takes effect. - This corresponds to the ``start_time`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.finding.Finding: - Security Command Center finding. - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([name, state, start_time]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.SetFindingStateRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - if state is not None: - request.state = state - if start_time is not None: - request.start_time = start_time - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_finding_state, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def set_iam_policy( - self, - request: iam_policy.SetIamPolicyRequest = None, - *, - resource: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: - r"""Sets the access control policy on the specified - Source. - - Args: - request (:class:`~.iam_policy.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - This corresponds to the ``resource`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([resource]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.SetIamPolicyRequest(**request) - - elif not request: - request = iam_policy.SetIamPolicyRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def test_iam_permissions( - self, - request: iam_policy.TestIamPermissionsRequest = None, - *, - resource: str = None, - permissions: Sequence[str] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: - r"""Returns the permissions that a caller has on the - specified source. - - Args: - request (:class:`~.iam_policy.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (:class:`Sequence[str]`): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - This corresponds to the ``permissions`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.iam_policy.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([resource, permissions]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.TestIamPermissionsRequest(**request) - - elif not request: - request = iam_policy.TestIamPermissionsRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource - - if permissions: - request.permissions.extend(permissions) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.test_iam_permissions, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def update_finding( - self, - request: securitycenter_service.UpdateFindingRequest = None, - *, - finding: gcs_finding.Finding = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Args: - request (:class:`~.securitycenter_service.UpdateFindingRequest`): - The request object. Request message for updating or - creating a finding. - finding (:class:`~.gcs_finding.Finding`): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the - name must alphanumeric and less than or equal to 32 - characters and greater than 0 characters in length. - This corresponds to the ``finding`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_finding.Finding: - Security Command Center finding. - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([finding]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.UpdateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_finding, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("finding.name", request.finding.name),) - ), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def update_organization_settings( - self, - request: securitycenter_service.UpdateOrganizationSettingsRequest = None, - *, - organization_settings: gcs_organization_settings.OrganizationSettings = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Updates an organization's settings. - - Args: - request (:class:`~.securitycenter_service.UpdateOrganizationSettingsRequest`): - The request object. Request message for updating an - organization's settings. - organization_settings (:class:`~.gcs_organization_settings.OrganizationSettings`): - Required. The organization settings - resource to update. - This corresponds to the ``organization_settings`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_organization_settings.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([organization_settings]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.UpdateOrganizationSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if organization_settings is not None: - request.organization_settings = organization_settings - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_organization_settings, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("organization_settings.name", request.organization_settings.name),) - ), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def update_source( - self, - request: securitycenter_service.UpdateSourceRequest = None, - *, - source: gcs_source.Source = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Updates a source. - - Args: - request (:class:`~.securitycenter_service.UpdateSourceRequest`): - The request object. Request message for updating a - source. - source (:class:`~.gcs_source.Source`): - Required. The source resource to - update. - This corresponds to the ``source`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([source]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.UpdateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_source, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("source.name", request.source.name),) - ), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def update_security_marks( - self, - request: securitycenter_service.UpdateSecurityMarksRequest = None, - *, - security_marks: gcs_security_marks.SecurityMarks = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_security_marks.SecurityMarks: - r"""Updates security marks. - - Args: - request (:class:`~.securitycenter_service.UpdateSecurityMarksRequest`): - The request object. Request message for updating a - SecurityMarks resource. - security_marks (:class:`~.gcs_security_marks.SecurityMarks`): - Required. The security marks resource - to update. - This corresponds to the ``security_marks`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_security_marks.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([security_marks]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.UpdateSecurityMarksRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if security_marks is not None: - request.security_marks = security_marks - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_security_marks, - default_timeout=480.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("security_marks.name", request.security_marks.name),) - ), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -try: - _client_info = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-securitycenter", - ).version, - ) -except pkg_resources.DistributionNotFound: - _client_info = gapic_v1.client_info.ClientInfo() - - -__all__ = ("SecurityCenterAsyncClient",) diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/client.py b/google/cloud/securitycenter_v1beta1/services/security_center/client.py deleted file mode 100644 index 2996fa09..00000000 --- a/google/cloud/securitycenter_v1beta1/services/security_center/client.py +++ /dev/null @@ -1,1933 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 -import os -import re -from typing import Callable, Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation -from google.api_core import operation_async -from google.cloud.securitycenter_v1beta1.services.security_center import pagers -from google.cloud.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import organization_settings -from google.cloud.securitycenter_v1beta1.types import ( - organization_settings as gcs_organization_settings, -) -from google.cloud.securitycenter_v1beta1.types import security_marks -from google.cloud.securitycenter_v1beta1.types import ( - security_marks as gcs_security_marks, -) -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - -from .transports.base import SecurityCenterTransport -from .transports.grpc import SecurityCenterGrpcTransport -from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport - - -class SecurityCenterClientMeta(type): - """Metaclass for the SecurityCenter 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[SecurityCenterTransport]] - _transport_registry["grpc"] = SecurityCenterGrpcTransport - _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport - - def get_transport_class(cls, label: str = None,) -> Type[SecurityCenterTransport]: - """Return 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 SecurityCenterClient(metaclass=SecurityCenterClientMeta): - """V1 Beta APIs for Security Center service.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Convert 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") - - DEFAULT_ENDPOINT = "securitycenter.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @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: - {@api.name}: 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 - - @staticmethod - def finding_path(organization: str, source: str, finding: str,) -> str: - """Return a fully-qualified finding string.""" - return "organizations/{organization}/sources/{source}/findings/{finding}".format( - organization=organization, source=source, finding=finding, - ) - - @staticmethod - def parse_finding_path(path: str) -> Dict[str, str]: - """Parse a finding path into its component segments.""" - m = re.match( - r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", - path, - ) - return m.groupdict() if m else {} - - @staticmethod - def organization_settings_path(organization: str,) -> str: - """Return a fully-qualified organization_settings string.""" - return "organizations/{organization}/organizationSettings".format( - organization=organization, - ) - - @staticmethod - def parse_organization_settings_path(path: str) -> Dict[str, str]: - """Parse a organization_settings path into its component segments.""" - m = re.match( - r"^organizations/(?P.+?)/organizationSettings$", path - ) - return m.groupdict() if m else {} - - @staticmethod - def security_marks_path(organization: str, asset: str,) -> str: - """Return a fully-qualified security_marks string.""" - return "organizations/{organization}/assets/{asset}/securityMarks".format( - organization=organization, asset=asset, - ) - - @staticmethod - def parse_security_marks_path(path: str) -> Dict[str, str]: - """Parse a security_marks path into its component segments.""" - m = re.match( - r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", - path, - ) - return m.groupdict() if m else {} - - @staticmethod - def source_path(organization: str, source: str,) -> str: - """Return a fully-qualified source string.""" - return "organizations/{organization}/sources/{source}".format( - organization=organization, source=source, - ) - - @staticmethod - def parse_source_path(path: str) -> Dict[str, str]: - """Parse a source path into its component segments.""" - m = re.match( - r"^organizations/(?P.+?)/sources/(?P.+?)$", path - ) - return m.groupdict() if m else {} - - def __init__( - self, - *, - credentials: credentials.Credentials = None, - transport: Union[str, SecurityCenterTransport] = None, - client_options: ClientOptions = None, - ) -> None: - """Instantiate the security center 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. - transport (Union[str, ~.SecurityCenterTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint, this is the default value for - the environment variable) and "auto" (auto switch to the default - mTLS endpoint if client SSL credentials is present). However, - the ``api_endpoint`` property takes precedence if provided. - (2) The ``client_cert_source`` property is used to provide client - SSL credentials for mutual TLS transport. If not provided, the - default SSL credentials will be used if present. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = ClientOptions.from_dict(client_options) - if client_options is None: - client_options = ClientOptions.ClientOptions() - - if client_options.api_endpoint is None: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") - if use_mtls_env == "never": - client_options.api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - has_client_cert_source = ( - client_options.client_cert_source is not None - or mtls.has_default_client_cert_source() - ) - client_options.api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT - if has_client_cert_source - else self.DEFAULT_ENDPOINT - ) - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, SecurityCenterTransport): - # transport is a SecurityCenterTransport instance. - if credentials or client_options.credentials_file: - raise ValueError( - "When providing a transport instance, " - "provide its credentials directly." - ) - if client_options.scopes: - raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=client_options.api_endpoint, - scopes=client_options.scopes, - api_mtls_endpoint=client_options.api_endpoint, - client_cert_source=client_options.client_cert_source, - quota_project_id=client_options.quota_project_id, - ) - - def create_source( - self, - request: securitycenter_service.CreateSourceRequest = None, - *, - parent: str = None, - source: gcs_source.Source = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Creates a source. - - Args: - request (:class:`~.securitycenter_service.CreateSourceRequest`): - The request object. Request message for creating a - source. - parent (:class:`str`): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (:class:`~.gcs_source.Source`): - Required. The Source being created, only the - display_name and description will be used. All other - fields will be ignored. - This corresponds to the ``source`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, source]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.CreateSourceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.CreateSourceRequest): - request = securitycenter_service.CreateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def create_finding( - self, - request: securitycenter_service.CreateFindingRequest = None, - *, - parent: str = None, - finding_id: str = None, - finding: gcs_finding.Finding = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Args: - request (:class:`~.securitycenter_service.CreateFindingRequest`): - The request object. Request message for creating a - finding. - parent (:class:`str`): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding_id (:class:`str`): - Required. Unique identifier provided - by the client within the parent scope. - It must be alphanumeric and less than or - equal to 32 characters and greater than - 0 characters in length. - This corresponds to the ``finding_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding (:class:`~.gcs_finding.Finding`): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output - only fields on this resource. - This corresponds to the ``finding`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_finding.Finding: - Security Command Center finding. - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, finding_id, finding]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.CreateFindingRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.CreateFindingRequest): - request = securitycenter_service.CreateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if finding_id is not None: - request.finding_id = finding_id - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_iam_policy( - self, - request: iam_policy.GetIamPolicyRequest = None, - *, - resource: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: - r"""Gets the access control policy on the specified - Source. - - Args: - request (:class:`~.iam_policy.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - This corresponds to the ``resource`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - 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." - ) - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.GetIamPolicyRequest(**request) - - elif not request: - request = iam_policy.GetIamPolicyRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_organization_settings( - self, - request: securitycenter_service.GetOrganizationSettingsRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> organization_settings.OrganizationSettings: - r"""Gets the settings for an organization. - - Args: - request (:class:`~.securitycenter_service.GetOrganizationSettingsRequest`): - The request object. Request message for getting - organization settings. - name (:class:`str`): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - This corresponds to the ``name`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.organization_settings.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.GetOrganizationSettingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance( - request, securitycenter_service.GetOrganizationSettingsRequest - ): - request = securitycenter_service.GetOrganizationSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.get_organization_settings - ] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_source( - self, - request: securitycenter_service.GetSourceRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> source.Source: - r"""Gets a source. - - Args: - request (:class:`~.securitycenter_service.GetSourceRequest`): - The request object. Request message for getting a - source. - name (:class:`str`): - Required. Relative resource name of the source. Its - format is - "organizations/[organization_id]/source/[source_id]". - This corresponds to the ``name`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.GetSourceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.GetSourceRequest): - request = securitycenter_service.GetSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def group_assets( - self, - request: securitycenter_service.GroupAssetsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupAssetsPager: - r"""Filters an organization's assets and groups them by - their specified properties. - - Args: - request (:class:`~.securitycenter_service.GroupAssetsRequest`): - The request object. Request message for grouping by - assets. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.GroupAssetsPager: - Response message for grouping by - assets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.GroupAssetsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.GroupAssetsRequest): - request = securitycenter_service.GroupAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.group_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.GroupAssetsPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - def group_findings( - self, - request: securitycenter_service.GroupFindingsRequest = None, - *, - parent: str = None, - group_by: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupFindingsPager: - r"""Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - Args: - request (:class:`~.securitycenter_service.GroupFindingsRequest`): - The request object. Request message for grouping by - findings. - parent (:class:`str`): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]". - To groupBy across all sources provide a source_id of - ``-``. For example: - organizations/{organization_id}/sources/- - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - group_by (:class:`str`): - Required. Expression that defines what assets fields to - use for grouping (including ``state``). The string value - should follow SQL syntax: comma separated list of - fields. For example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - This corresponds to the ``group_by`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.GroupFindingsPager: - Response message for group by - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, group_by]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.GroupFindingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.GroupFindingsRequest): - request = securitycenter_service.GroupFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.group_findings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.GroupFindingsPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - def list_assets( - self, - request: securitycenter_service.ListAssetsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAssetsPager: - r"""Lists an organization's assets. - - Args: - request (:class:`~.securitycenter_service.ListAssetsRequest`): - The request object. Request message for listing assets. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.ListAssetsPager: - Response message for listing assets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.ListAssetsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.ListAssetsRequest): - request = securitycenter_service.ListAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListAssetsPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - def list_findings( - self, - request: securitycenter_service.ListFindingsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFindingsPager: - r"""Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - Args: - request (:class:`~.securitycenter_service.ListFindingsRequest`): - The request object. Request message for listing - findings. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.ListFindingsPager: - Response message for listing - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.ListFindingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.ListFindingsRequest): - request = securitycenter_service.ListFindingsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_findings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListFindingsPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - def list_sources( - self, - request: securitycenter_service.ListSourcesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSourcesPager: - r"""Lists all sources belonging to an organization. - - Args: - request (:class:`~.securitycenter_service.ListSourcesRequest`): - The request object. Request message for listing sources. - parent (:class:`str`): - Required. Resource name of the parent of sources to - list. Its format should be - "organizations/[organization_id]". - This corresponds to the ``parent`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.ListSourcesPager: - Response message for listing sources. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.ListSourcesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.ListSourcesRequest): - request = securitycenter_service.ListSourcesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_sources] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListSourcesPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - def run_asset_discovery( - self, - request: securitycenter_service.RunAssetDiscoveryRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Args: - request (:class:`~.securitycenter_service.RunAssetDiscoveryRequest`): - The request object. Request message for running asset - discovery for an organization. - parent (:class:`str`): - Required. Name of the organization to run asset - discovery for. Its format is - "organizations/[organization_id]". - This corresponds to the ``parent`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:``~.empty.Empty``: A generic empty message that - you can re-use to avoid defining duplicated empty - messages in your APIs. A typical example is to use it as - the request or the response type of an API method. For - instance: - - :: - - service Foo { - rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); - } - - The JSON representation for ``Empty`` is empty JSON - object ``{}``. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.RunAssetDiscoveryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.RunAssetDiscoveryRequest): - request = securitycenter_service.RunAssetDiscoveryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.run_asset_discovery] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - empty.Empty, - metadata_type=empty.Empty, - ) - - # Done; return the response. - return response - - def set_finding_state( - self, - request: securitycenter_service.SetFindingStateRequest = None, - *, - name: str = None, - state: finding.Finding.State = None, - start_time: timestamp.Timestamp = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the state of a finding. - - Args: - request (:class:`~.securitycenter_service.SetFindingStateRequest`): - The request object. Request message for updating a - finding's state. - name (:class:`str`): - Required. The relative resource name of the finding. - See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - state (:class:`~.finding.Finding.State`): - Required. The desired State of the - finding. - This corresponds to the ``state`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - start_time (:class:`~.timestamp.Timestamp`): - Required. The time at which the - updated state takes effect. - This corresponds to the ``start_time`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.finding.Finding: - Security Command Center finding. - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, state, start_time]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.SetFindingStateRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.SetFindingStateRequest): - request = securitycenter_service.SetFindingStateRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - if state is not None: - request.state = state - if start_time is not None: - request.start_time = start_time - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_finding_state] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def set_iam_policy( - self, - request: iam_policy.SetIamPolicyRequest = None, - *, - resource: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: - r"""Sets the access control policy on the specified - Source. - - Args: - request (:class:`~.iam_policy.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - This corresponds to the ``resource`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - 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." - ) - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.SetIamPolicyRequest(**request) - - elif not request: - request = iam_policy.SetIamPolicyRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def test_iam_permissions( - self, - request: iam_policy.TestIamPermissionsRequest = None, - *, - resource: str = None, - permissions: Sequence[str] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: - r"""Returns the permissions that a caller has on the - specified source. - - Args: - request (:class:`~.iam_policy.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (:class:`Sequence[str]`): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - This corresponds to the ``permissions`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.iam_policy.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource, permissions]) - 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." - ) - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.TestIamPermissionsRequest(**request) - - elif not request: - request = iam_policy.TestIamPermissionsRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource - - if permissions: - request.permissions.extend(permissions) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def update_finding( - self, - request: securitycenter_service.UpdateFindingRequest = None, - *, - finding: gcs_finding.Finding = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Args: - request (:class:`~.securitycenter_service.UpdateFindingRequest`): - The request object. Request message for updating or - creating a finding. - finding (:class:`~.gcs_finding.Finding`): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the - name must alphanumeric and less than or equal to 32 - characters and greater than 0 characters in length. - This corresponds to the ``finding`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_finding.Finding: - Security Command Center finding. - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([finding]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.UpdateFindingRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.UpdateFindingRequest): - request = securitycenter_service.UpdateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("finding.name", request.finding.name),) - ), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def update_organization_settings( - self, - request: securitycenter_service.UpdateOrganizationSettingsRequest = None, - *, - organization_settings: gcs_organization_settings.OrganizationSettings = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Updates an organization's settings. - - Args: - request (:class:`~.securitycenter_service.UpdateOrganizationSettingsRequest`): - The request object. Request message for updating an - organization's settings. - organization_settings (:class:`~.gcs_organization_settings.OrganizationSettings`): - Required. The organization settings - resource to update. - This corresponds to the ``organization_settings`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_organization_settings.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([organization_settings]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.UpdateOrganizationSettingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance( - request, securitycenter_service.UpdateOrganizationSettingsRequest - ): - request = securitycenter_service.UpdateOrganizationSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if organization_settings is not None: - request.organization_settings = organization_settings - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.update_organization_settings - ] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("organization_settings.name", request.organization_settings.name),) - ), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def update_source( - self, - request: securitycenter_service.UpdateSourceRequest = None, - *, - source: gcs_source.Source = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Updates a source. - - Args: - request (:class:`~.securitycenter_service.UpdateSourceRequest`): - The request object. Request message for updating a - source. - source (:class:`~.gcs_source.Source`): - Required. The source resource to - update. - This corresponds to the ``source`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([source]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.UpdateSourceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.UpdateSourceRequest): - request = securitycenter_service.UpdateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("source.name", request.source.name),) - ), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def update_security_marks( - self, - request: securitycenter_service.UpdateSecurityMarksRequest = None, - *, - security_marks: gcs_security_marks.SecurityMarks = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_security_marks.SecurityMarks: - r"""Updates security marks. - - Args: - request (:class:`~.securitycenter_service.UpdateSecurityMarksRequest`): - The request object. Request message for updating a - SecurityMarks resource. - security_marks (:class:`~.gcs_security_marks.SecurityMarks`): - Required. The security marks resource - to update. - This corresponds to the ``security_marks`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_security_marks.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_marks]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.UpdateSecurityMarksRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): - request = securitycenter_service.UpdateSecurityMarksRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if security_marks is not None: - request.security_marks = security_marks - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.update_security_marks] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("security_marks.name", request.security_marks.name),) - ), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -try: - _client_info = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-securitycenter", - ).version, - ) -except pkg_resources.DistributionNotFound: - _client_info = gapic_v1.client_info.ClientInfo() - - -__all__ = ("SecurityCenterClient",) diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py b/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py deleted file mode 100644 index 64ef79bd..00000000 --- a/google/cloud/securitycenter_v1beta1/services/security_center/pagers.py +++ /dev/null @@ -1,668 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple - -from google.cloud.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source - - -class GroupAssetsPager: - """A pager for iterating through ``group_assets`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.GroupAssetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``GroupAssets`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.GroupAssetsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., securitycenter_service.GroupAssetsResponse], - request: securitycenter_service.GroupAssetsRequest, - response: securitycenter_service.GroupAssetsResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.GroupAssetsRequest`): - The initial request object. - response (:class:`~.securitycenter_service.GroupAssetsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.GroupAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.GroupAssetsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[securitycenter_service.GroupResult]: - for page in self.pages: - yield from page.group_by_results - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class GroupAssetsAsyncPager: - """A pager for iterating through ``group_assets`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.GroupAssetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``GroupAssets`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.GroupAssetsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., Awaitable[securitycenter_service.GroupAssetsResponse]], - request: securitycenter_service.GroupAssetsRequest, - response: securitycenter_service.GroupAssetsResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.GroupAssetsRequest`): - The initial request object. - response (:class:`~.securitycenter_service.GroupAssetsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.GroupAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.GroupAssetsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[securitycenter_service.GroupResult]: - async def async_generator(): - async for page in self.pages: - for response in page.group_by_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class GroupFindingsPager: - """A pager for iterating through ``group_findings`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.GroupFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``GroupFindings`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.GroupFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., securitycenter_service.GroupFindingsResponse], - request: securitycenter_service.GroupFindingsRequest, - response: securitycenter_service.GroupFindingsResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.GroupFindingsRequest`): - The initial request object. - response (:class:`~.securitycenter_service.GroupFindingsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.GroupFindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.GroupFindingsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[securitycenter_service.GroupResult]: - for page in self.pages: - yield from page.group_by_results - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class GroupFindingsAsyncPager: - """A pager for iterating through ``group_findings`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.GroupFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``GroupFindings`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.GroupFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., Awaitable[securitycenter_service.GroupFindingsResponse]], - request: securitycenter_service.GroupFindingsRequest, - response: securitycenter_service.GroupFindingsResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.GroupFindingsRequest`): - The initial request object. - response (:class:`~.securitycenter_service.GroupFindingsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.GroupFindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages( - self, - ) -> AsyncIterable[securitycenter_service.GroupFindingsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[securitycenter_service.GroupResult]: - async def async_generator(): - async for page in self.pages: - for response in page.group_by_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListAssetsPager: - """A pager for iterating through ``list_assets`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.ListAssetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``list_assets_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAssets`` requests and continue to iterate - through the ``list_assets_results`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.ListAssetsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., securitycenter_service.ListAssetsResponse], - request: securitycenter_service.ListAssetsRequest, - response: securitycenter_service.ListAssetsResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.ListAssetsRequest`): - The initial request object. - response (:class:`~.securitycenter_service.ListAssetsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.ListAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.ListAssetsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__( - self, - ) -> Iterable[securitycenter_service.ListAssetsResponse.ListAssetsResult]: - for page in self.pages: - yield from page.list_assets_results - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListAssetsAsyncPager: - """A pager for iterating through ``list_assets`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.ListAssetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``list_assets_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAssets`` requests and continue to iterate - through the ``list_assets_results`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.ListAssetsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., Awaitable[securitycenter_service.ListAssetsResponse]], - request: securitycenter_service.ListAssetsRequest, - response: securitycenter_service.ListAssetsResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.ListAssetsRequest`): - The initial request object. - response (:class:`~.securitycenter_service.ListAssetsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.ListAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.ListAssetsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__( - self, - ) -> AsyncIterable[securitycenter_service.ListAssetsResponse.ListAssetsResult]: - async def async_generator(): - async for page in self.pages: - for response in page.list_assets_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListFindingsPager: - """A pager for iterating through ``list_findings`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.ListFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``findings`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``findings`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.ListFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., securitycenter_service.ListFindingsResponse], - request: securitycenter_service.ListFindingsRequest, - response: securitycenter_service.ListFindingsResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.ListFindingsRequest`): - The initial request object. - response (:class:`~.securitycenter_service.ListFindingsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.ListFindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.ListFindingsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[finding.Finding]: - for page in self.pages: - yield from page.findings - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListFindingsAsyncPager: - """A pager for iterating through ``list_findings`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.ListFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``findings`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``findings`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.ListFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., Awaitable[securitycenter_service.ListFindingsResponse]], - request: securitycenter_service.ListFindingsRequest, - response: securitycenter_service.ListFindingsResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.ListFindingsRequest`): - The initial request object. - response (:class:`~.securitycenter_service.ListFindingsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.ListFindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.ListFindingsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[finding.Finding]: - async def async_generator(): - async for page in self.pages: - for response in page.findings: - yield response - - return async_generator() - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListSourcesPager: - """A pager for iterating through ``list_sources`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.ListSourcesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``sources`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSources`` requests and continue to iterate - through the ``sources`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.ListSourcesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., securitycenter_service.ListSourcesResponse], - request: securitycenter_service.ListSourcesRequest, - response: securitycenter_service.ListSourcesResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.ListSourcesRequest`): - The initial request object. - response (:class:`~.securitycenter_service.ListSourcesResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.ListSourcesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.ListSourcesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[source.Source]: - for page in self.pages: - yield from page.sources - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListSourcesAsyncPager: - """A pager for iterating through ``list_sources`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.ListSourcesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``sources`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSources`` requests and continue to iterate - through the ``sources`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.ListSourcesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., Awaitable[securitycenter_service.ListSourcesResponse]], - request: securitycenter_service.ListSourcesRequest, - response: securitycenter_service.ListSourcesResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.ListSourcesRequest`): - The initial request object. - response (:class:`~.securitycenter_service.ListSourcesResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.ListSourcesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.ListSourcesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[source.Source]: - async def async_generator(): - async for page in self.pages: - for response in page.sources: - yield response - - return async_generator() - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py b/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py deleted file mode 100644 index 20423f2a..00000000 --- a/google/cloud/securitycenter_v1beta1/services/security_center/transports/__init__.py +++ /dev/null @@ -1,36 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 typing import Dict, Type - -from .base import SecurityCenterTransport -from .grpc import SecurityCenterGrpcTransport -from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] -_transport_registry["grpc"] = SecurityCenterGrpcTransport -_transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport - - -__all__ = ( - "SecurityCenterTransport", - "SecurityCenterGrpcTransport", - "SecurityCenterGrpcAsyncIOTransport", -) diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py b/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py deleted file mode 100644 index 52252676..00000000 --- a/google/cloud/securitycenter_v1beta1/services/security_center/transports/base.py +++ /dev/null @@ -1,465 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 -import typing -import pkg_resources - -from google import auth -from google.api_core import exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore - -from google.cloud.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import organization_settings -from google.cloud.securitycenter_v1beta1.types import ( - organization_settings as gcs_organization_settings, -) -from google.cloud.securitycenter_v1beta1.types import ( - security_marks as gcs_security_marks, -) -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.longrunning import operations_pb2 as operations # type: ignore - - -try: - _client_info = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-securitycenter", - ).version, - ) -except pkg_resources.DistributionNotFound: - _client_info = gapic_v1.client_info.ClientInfo() - - -class SecurityCenterTransport(abc.ABC): - """Abstract transport class for SecurityCenter.""" - - AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - - def __init__( - self, - *, - host: str = "securitycenter.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): The hostname to connect to. - 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]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) - - if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id - ) - - # Save the credentials. - self._credentials = credentials - - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages() - - def _prep_wrapped_messages(self): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_source: gapic_v1.method.wrap_method( - self.create_source, default_timeout=60.0, client_info=_client_info, - ), - self.create_finding: gapic_v1.method.wrap_method( - self.create_finding, default_timeout=60.0, client_info=_client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ), - self.get_organization_settings: gapic_v1.method.wrap_method( - self.get_organization_settings, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ), - self.get_source: gapic_v1.method.wrap_method( - self.get_source, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ), - self.group_assets: gapic_v1.method.wrap_method( - self.group_assets, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ), - self.group_findings: gapic_v1.method.wrap_method( - self.group_findings, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ), - self.list_assets: gapic_v1.method.wrap_method( - self.list_assets, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ), - self.list_findings: gapic_v1.method.wrap_method( - self.list_findings, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ), - self.list_sources: gapic_v1.method.wrap_method( - self.list_sources, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ), - self.run_asset_discovery: gapic_v1.method.wrap_method( - self.run_asset_discovery, - default_timeout=60.0, - client_info=_client_info, - ), - self.set_finding_state: gapic_v1.method.wrap_method( - self.set_finding_state, default_timeout=60.0, client_info=_client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, default_timeout=60.0, client_info=_client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ), - self.update_finding: gapic_v1.method.wrap_method( - self.update_finding, default_timeout=60.0, client_info=_client_info, - ), - self.update_organization_settings: gapic_v1.method.wrap_method( - self.update_organization_settings, - default_timeout=60.0, - client_info=_client_info, - ), - self.update_source: gapic_v1.method.wrap_method( - self.update_source, default_timeout=60.0, client_info=_client_info, - ), - self.update_security_marks: gapic_v1.method.wrap_method( - self.update_security_marks, - default_timeout=480.0, - client_info=_client_info, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_source( - self, - ) -> typing.Callable[ - [securitycenter_service.CreateSourceRequest], - typing.Union[gcs_source.Source, typing.Awaitable[gcs_source.Source]], - ]: - raise NotImplementedError() - - @property - def create_finding( - self, - ) -> typing.Callable[ - [securitycenter_service.CreateFindingRequest], - typing.Union[gcs_finding.Finding, typing.Awaitable[gcs_finding.Finding]], - ]: - raise NotImplementedError() - - @property - def get_iam_policy( - self, - ) -> typing.Callable[ - [iam_policy.GetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], - ]: - raise NotImplementedError() - - @property - def get_organization_settings( - self, - ) -> typing.Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - typing.Union[ - organization_settings.OrganizationSettings, - typing.Awaitable[organization_settings.OrganizationSettings], - ], - ]: - raise NotImplementedError() - - @property - def get_source( - self, - ) -> typing.Callable[ - [securitycenter_service.GetSourceRequest], - typing.Union[source.Source, typing.Awaitable[source.Source]], - ]: - raise NotImplementedError() - - @property - def group_assets( - self, - ) -> typing.Callable[ - [securitycenter_service.GroupAssetsRequest], - typing.Union[ - securitycenter_service.GroupAssetsResponse, - typing.Awaitable[securitycenter_service.GroupAssetsResponse], - ], - ]: - raise NotImplementedError() - - @property - def group_findings( - self, - ) -> typing.Callable[ - [securitycenter_service.GroupFindingsRequest], - typing.Union[ - securitycenter_service.GroupFindingsResponse, - typing.Awaitable[securitycenter_service.GroupFindingsResponse], - ], - ]: - raise NotImplementedError() - - @property - def list_assets( - self, - ) -> typing.Callable[ - [securitycenter_service.ListAssetsRequest], - typing.Union[ - securitycenter_service.ListAssetsResponse, - typing.Awaitable[securitycenter_service.ListAssetsResponse], - ], - ]: - raise NotImplementedError() - - @property - def list_findings( - self, - ) -> typing.Callable[ - [securitycenter_service.ListFindingsRequest], - typing.Union[ - securitycenter_service.ListFindingsResponse, - typing.Awaitable[securitycenter_service.ListFindingsResponse], - ], - ]: - raise NotImplementedError() - - @property - def list_sources( - self, - ) -> typing.Callable[ - [securitycenter_service.ListSourcesRequest], - typing.Union[ - securitycenter_service.ListSourcesResponse, - typing.Awaitable[securitycenter_service.ListSourcesResponse], - ], - ]: - raise NotImplementedError() - - @property - def run_asset_discovery( - self, - ) -> typing.Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], - ]: - raise NotImplementedError() - - @property - def set_finding_state( - self, - ) -> typing.Callable[ - [securitycenter_service.SetFindingStateRequest], - typing.Union[finding.Finding, typing.Awaitable[finding.Finding]], - ]: - raise NotImplementedError() - - @property - def set_iam_policy( - self, - ) -> typing.Callable[ - [iam_policy.SetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], - ]: - raise NotImplementedError() - - @property - def test_iam_permissions( - self, - ) -> typing.Callable[ - [iam_policy.TestIamPermissionsRequest], - typing.Union[ - iam_policy.TestIamPermissionsResponse, - typing.Awaitable[iam_policy.TestIamPermissionsResponse], - ], - ]: - raise NotImplementedError() - - @property - def update_finding( - self, - ) -> typing.Callable[ - [securitycenter_service.UpdateFindingRequest], - typing.Union[gcs_finding.Finding, typing.Awaitable[gcs_finding.Finding]], - ]: - raise NotImplementedError() - - @property - def update_organization_settings( - self, - ) -> typing.Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - typing.Union[ - gcs_organization_settings.OrganizationSettings, - typing.Awaitable[gcs_organization_settings.OrganizationSettings], - ], - ]: - raise NotImplementedError() - - @property - def update_source( - self, - ) -> typing.Callable[ - [securitycenter_service.UpdateSourceRequest], - typing.Union[gcs_source.Source, typing.Awaitable[gcs_source.Source]], - ]: - raise NotImplementedError() - - @property - def update_security_marks( - self, - ) -> typing.Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - typing.Union[ - gcs_security_marks.SecurityMarks, - typing.Awaitable[gcs_security_marks.SecurityMarks], - ], - ]: - raise NotImplementedError() - - -__all__ = ("SecurityCenterTransport",) diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py b/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py deleted file mode 100644 index 37b8b413..00000000 --- a/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc.py +++ /dev/null @@ -1,754 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 typing import Callable, Dict, Optional, Sequence, Tuple - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - - -import grpc # type: ignore - -from google.cloud.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import organization_settings -from google.cloud.securitycenter_v1beta1.types import ( - organization_settings as gcs_organization_settings, -) -from google.cloud.securitycenter_v1beta1.types import ( - security_marks as gcs_security_marks, -) -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.longrunning import operations_pb2 as operations # type: ignore - -from .base import SecurityCenterTransport - - -class SecurityCenterGrpcTransport(SecurityCenterTransport): - """gRPC backend transport for SecurityCenter. - - V1 Beta APIs for Security Center service. - - 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 = "securitycenter.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): The hostname to connect to. - 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 ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): 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 applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 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. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - - 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. - """ - if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. - credentials = False - - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - ) - - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - ) - - @classmethod - def create_channel( - cls, - host: str = "securitycenter.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs - ) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - address (Optionsl[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]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional 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. - """ - scopes = scopes or cls.AUTH_SCOPES - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Sanity check: Only create a new channel if we do not already - # have one. - if not hasattr(self, "_grpc_channel"): - self._grpc_channel = self.create_channel( - self._host, credentials=self._credentials, - ) - - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if "operations_client" not in self.__dict__: - self.__dict__["operations_client"] = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self.__dict__["operations_client"] - - @property - def create_source( - self, - ) -> Callable[[securitycenter_service.CreateSourceRequest], gcs_source.Source]: - r"""Return a callable for the create source method over gRPC. - - Creates a source. - - Returns: - Callable[[~.CreateSourceRequest], - ~.Source]: - 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_source" not in self._stubs: - self._stubs["create_source"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateSource", - request_serializer=securitycenter_service.CreateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs["create_source"] - - @property - def create_finding( - self, - ) -> Callable[[securitycenter_service.CreateFindingRequest], gcs_finding.Finding]: - r"""Return a callable for the create finding method over gRPC. - - Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Returns: - Callable[[~.CreateFindingRequest], - ~.Finding]: - 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_finding" not in self._stubs: - self._stubs["create_finding"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateFinding", - request_serializer=securitycenter_service.CreateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs["create_finding"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy.GetIamPolicyRequest], policy.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the access control policy on the specified - Source. - - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - 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 "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/GetIamPolicy", - request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def get_organization_settings( - self, - ) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - organization_settings.OrganizationSettings, - ]: - r"""Return a callable for the get organization settings method over gRPC. - - Gets the settings for an organization. - - Returns: - Callable[[~.GetOrganizationSettingsRequest], - ~.OrganizationSettings]: - 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 "get_organization_settings" not in self._stubs: - self._stubs["get_organization_settings"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/GetOrganizationSettings", - request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, - response_deserializer=organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs["get_organization_settings"] - - @property - def get_source( - self, - ) -> Callable[[securitycenter_service.GetSourceRequest], source.Source]: - r"""Return a callable for the get source method over gRPC. - - Gets a source. - - Returns: - Callable[[~.GetSourceRequest], - ~.Source]: - 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 "get_source" not in self._stubs: - self._stubs["get_source"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/GetSource", - request_serializer=securitycenter_service.GetSourceRequest.serialize, - response_deserializer=source.Source.deserialize, - ) - return self._stubs["get_source"] - - @property - def group_assets( - self, - ) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - securitycenter_service.GroupAssetsResponse, - ]: - r"""Return a callable for the group assets method over gRPC. - - Filters an organization's assets and groups them by - their specified properties. - - Returns: - Callable[[~.GroupAssetsRequest], - ~.GroupAssetsResponse]: - 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 "group_assets" not in self._stubs: - self._stubs["group_assets"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupAssets", - request_serializer=securitycenter_service.GroupAssetsRequest.serialize, - response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, - ) - return self._stubs["group_assets"] - - @property - def group_findings( - self, - ) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - securitycenter_service.GroupFindingsResponse, - ]: - r"""Return a callable for the group findings method over gRPC. - - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - Returns: - Callable[[~.GroupFindingsRequest], - ~.GroupFindingsResponse]: - 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 "group_findings" not in self._stubs: - self._stubs["group_findings"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupFindings", - request_serializer=securitycenter_service.GroupFindingsRequest.serialize, - response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, - ) - return self._stubs["group_findings"] - - @property - def list_assets( - self, - ) -> Callable[ - [securitycenter_service.ListAssetsRequest], - securitycenter_service.ListAssetsResponse, - ]: - r"""Return a callable for the list assets method over gRPC. - - Lists an organization's assets. - - Returns: - Callable[[~.ListAssetsRequest], - ~.ListAssetsResponse]: - 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 "list_assets" not in self._stubs: - self._stubs["list_assets"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/ListAssets", - request_serializer=securitycenter_service.ListAssetsRequest.serialize, - response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, - ) - return self._stubs["list_assets"] - - @property - def list_findings( - self, - ) -> Callable[ - [securitycenter_service.ListFindingsRequest], - securitycenter_service.ListFindingsResponse, - ]: - r"""Return a callable for the list findings method over gRPC. - - Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - Returns: - Callable[[~.ListFindingsRequest], - ~.ListFindingsResponse]: - 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 "list_findings" not in self._stubs: - self._stubs["list_findings"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/ListFindings", - request_serializer=securitycenter_service.ListFindingsRequest.serialize, - response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, - ) - return self._stubs["list_findings"] - - @property - def list_sources( - self, - ) -> Callable[ - [securitycenter_service.ListSourcesRequest], - securitycenter_service.ListSourcesResponse, - ]: - r"""Return a callable for the list sources method over gRPC. - - Lists all sources belonging to an organization. - - Returns: - Callable[[~.ListSourcesRequest], - ~.ListSourcesResponse]: - 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 "list_sources" not in self._stubs: - self._stubs["list_sources"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/ListSources", - request_serializer=securitycenter_service.ListSourcesRequest.serialize, - response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, - ) - return self._stubs["list_sources"] - - @property - def run_asset_discovery( - self, - ) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], operations.Operation - ]: - r"""Return a callable for the run asset discovery method over gRPC. - - Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Returns: - Callable[[~.RunAssetDiscoveryRequest], - ~.Operation]: - 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 "run_asset_discovery" not in self._stubs: - self._stubs["run_asset_discovery"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/RunAssetDiscovery", - request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations.Operation.FromString, - ) - return self._stubs["run_asset_discovery"] - - @property - def set_finding_state( - self, - ) -> Callable[[securitycenter_service.SetFindingStateRequest], finding.Finding]: - r"""Return a callable for the set finding state method over gRPC. - - Updates the state of a finding. - - Returns: - Callable[[~.SetFindingStateRequest], - ~.Finding]: - 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 "set_finding_state" not in self._stubs: - self._stubs["set_finding_state"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/SetFindingState", - request_serializer=securitycenter_service.SetFindingStateRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs["set_finding_state"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], policy.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets the access control policy on the specified - Source. - - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - 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 "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/SetIamPolicy", - request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], iam_policy.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - - Returns the permissions that a caller has on the - specified source. - - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - 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 "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/TestIamPermissions", - request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - @property - def update_finding( - self, - ) -> Callable[[securitycenter_service.UpdateFindingRequest], gcs_finding.Finding]: - r"""Return a callable for the update finding method over gRPC. - - Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Returns: - Callable[[~.UpdateFindingRequest], - ~.Finding]: - 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_finding" not in self._stubs: - self._stubs["update_finding"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateFinding", - request_serializer=securitycenter_service.UpdateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs["update_finding"] - - @property - def update_organization_settings( - self, - ) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - gcs_organization_settings.OrganizationSettings, - ]: - r"""Return a callable for the update organization settings method over gRPC. - - Updates an organization's settings. - - Returns: - Callable[[~.UpdateOrganizationSettingsRequest], - ~.OrganizationSettings]: - 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_organization_settings" not in self._stubs: - self._stubs["update_organization_settings"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateOrganizationSettings", - request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, - response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs["update_organization_settings"] - - @property - def update_source( - self, - ) -> Callable[[securitycenter_service.UpdateSourceRequest], gcs_source.Source]: - r"""Return a callable for the update source method over gRPC. - - Updates a source. - - Returns: - Callable[[~.UpdateSourceRequest], - ~.Source]: - 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_source" not in self._stubs: - self._stubs["update_source"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSource", - request_serializer=securitycenter_service.UpdateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs["update_source"] - - @property - def update_security_marks( - self, - ) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - gcs_security_marks.SecurityMarks, - ]: - r"""Return a callable for the update security marks method over gRPC. - - Updates security marks. - - Returns: - Callable[[~.UpdateSecurityMarksRequest], - ~.SecurityMarks]: - 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_security_marks" not in self._stubs: - self._stubs["update_security_marks"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSecurityMarks", - request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, - response_deserializer=gcs_security_marks.SecurityMarks.deserialize, - ) - return self._stubs["update_security_marks"] - - -__all__ = ("SecurityCenterGrpcTransport",) diff --git a/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py b/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py deleted file mode 100644 index c3d7b5db..00000000 --- a/google/cloud/securitycenter_v1beta1/services/security_center/transports/grpc_asyncio.py +++ /dev/null @@ -1,759 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple - -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.securitycenter_v1beta1.types import finding -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import organization_settings -from google.cloud.securitycenter_v1beta1.types import ( - organization_settings as gcs_organization_settings, -) -from google.cloud.securitycenter_v1beta1.types import ( - security_marks as gcs_security_marks, -) -from google.cloud.securitycenter_v1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1beta1.types import source -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.longrunning import operations_pb2 as operations # type: ignore - -from .base import SecurityCenterTransport -from .grpc import SecurityCenterGrpcTransport - - -class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): - """gRPC AsyncIO backend transport for SecurityCenter. - - V1 Beta APIs for Security Center service. - - 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 = "securitycenter.googleapis.com", - credentials: 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: - address (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]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional 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. - """ - scopes = scopes or cls.AUTH_SCOPES - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - **kwargs, - ) - - def __init__( - self, - *, - host: str = "securitycenter.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): The hostname to connect to. - 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 ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional 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[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): 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 applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 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. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - - 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. - """ - if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. - credentials = False - - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - ) - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - ) - - self._stubs = {} - - @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. - """ - # Sanity check: Only create a new channel if we do not already - # have one. - if not hasattr(self, "_grpc_channel"): - self._grpc_channel = self.create_channel( - self._host, credentials=self._credentials, - ) - - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if "operations_client" not in self.__dict__: - self.__dict__["operations_client"] = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self.__dict__["operations_client"] - - @property - def create_source( - self, - ) -> Callable[ - [securitycenter_service.CreateSourceRequest], Awaitable[gcs_source.Source] - ]: - r"""Return a callable for the create source method over gRPC. - - Creates a source. - - Returns: - Callable[[~.CreateSourceRequest], - Awaitable[~.Source]]: - 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_source" not in self._stubs: - self._stubs["create_source"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateSource", - request_serializer=securitycenter_service.CreateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs["create_source"] - - @property - def create_finding( - self, - ) -> Callable[ - [securitycenter_service.CreateFindingRequest], Awaitable[gcs_finding.Finding] - ]: - r"""Return a callable for the create finding method over gRPC. - - Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Returns: - Callable[[~.CreateFindingRequest], - Awaitable[~.Finding]]: - 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_finding" not in self._stubs: - self._stubs["create_finding"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/CreateFinding", - request_serializer=securitycenter_service.CreateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs["create_finding"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy.GetIamPolicyRequest], Awaitable[policy.Policy]]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the access control policy on the specified - Source. - - Returns: - Callable[[~.GetIamPolicyRequest], - Awaitable[~.Policy]]: - 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 "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/GetIamPolicy", - request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def get_organization_settings( - self, - ) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - Awaitable[organization_settings.OrganizationSettings], - ]: - r"""Return a callable for the get organization settings method over gRPC. - - Gets the settings for an organization. - - Returns: - Callable[[~.GetOrganizationSettingsRequest], - Awaitable[~.OrganizationSettings]]: - 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 "get_organization_settings" not in self._stubs: - self._stubs["get_organization_settings"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/GetOrganizationSettings", - request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, - response_deserializer=organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs["get_organization_settings"] - - @property - def get_source( - self, - ) -> Callable[[securitycenter_service.GetSourceRequest], Awaitable[source.Source]]: - r"""Return a callable for the get source method over gRPC. - - Gets a source. - - Returns: - Callable[[~.GetSourceRequest], - Awaitable[~.Source]]: - 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 "get_source" not in self._stubs: - self._stubs["get_source"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/GetSource", - request_serializer=securitycenter_service.GetSourceRequest.serialize, - response_deserializer=source.Source.deserialize, - ) - return self._stubs["get_source"] - - @property - def group_assets( - self, - ) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - Awaitable[securitycenter_service.GroupAssetsResponse], - ]: - r"""Return a callable for the group assets method over gRPC. - - Filters an organization's assets and groups them by - their specified properties. - - Returns: - Callable[[~.GroupAssetsRequest], - Awaitable[~.GroupAssetsResponse]]: - 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 "group_assets" not in self._stubs: - self._stubs["group_assets"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupAssets", - request_serializer=securitycenter_service.GroupAssetsRequest.serialize, - response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, - ) - return self._stubs["group_assets"] - - @property - def group_findings( - self, - ) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - Awaitable[securitycenter_service.GroupFindingsResponse], - ]: - r"""Return a callable for the group findings method over gRPC. - - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - Returns: - Callable[[~.GroupFindingsRequest], - Awaitable[~.GroupFindingsResponse]]: - 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 "group_findings" not in self._stubs: - self._stubs["group_findings"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/GroupFindings", - request_serializer=securitycenter_service.GroupFindingsRequest.serialize, - response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, - ) - return self._stubs["group_findings"] - - @property - def list_assets( - self, - ) -> Callable[ - [securitycenter_service.ListAssetsRequest], - Awaitable[securitycenter_service.ListAssetsResponse], - ]: - r"""Return a callable for the list assets method over gRPC. - - Lists an organization's assets. - - Returns: - Callable[[~.ListAssetsRequest], - Awaitable[~.ListAssetsResponse]]: - 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 "list_assets" not in self._stubs: - self._stubs["list_assets"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/ListAssets", - request_serializer=securitycenter_service.ListAssetsRequest.serialize, - response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, - ) - return self._stubs["list_assets"] - - @property - def list_findings( - self, - ) -> Callable[ - [securitycenter_service.ListFindingsRequest], - Awaitable[securitycenter_service.ListFindingsResponse], - ]: - r"""Return a callable for the list findings method over gRPC. - - Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1beta1/organizations/{organization_id}/sources/-/findings - - Returns: - Callable[[~.ListFindingsRequest], - Awaitable[~.ListFindingsResponse]]: - 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 "list_findings" not in self._stubs: - self._stubs["list_findings"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/ListFindings", - request_serializer=securitycenter_service.ListFindingsRequest.serialize, - response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, - ) - return self._stubs["list_findings"] - - @property - def list_sources( - self, - ) -> Callable[ - [securitycenter_service.ListSourcesRequest], - Awaitable[securitycenter_service.ListSourcesResponse], - ]: - r"""Return a callable for the list sources method over gRPC. - - Lists all sources belonging to an organization. - - Returns: - Callable[[~.ListSourcesRequest], - Awaitable[~.ListSourcesResponse]]: - 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 "list_sources" not in self._stubs: - self._stubs["list_sources"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/ListSources", - request_serializer=securitycenter_service.ListSourcesRequest.serialize, - response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, - ) - return self._stubs["list_sources"] - - @property - def run_asset_discovery( - self, - ) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - Awaitable[operations.Operation], - ]: - r"""Return a callable for the run asset discovery method over gRPC. - - Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Returns: - Callable[[~.RunAssetDiscoveryRequest], - Awaitable[~.Operation]]: - 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 "run_asset_discovery" not in self._stubs: - self._stubs["run_asset_discovery"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/RunAssetDiscovery", - request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations.Operation.FromString, - ) - return self._stubs["run_asset_discovery"] - - @property - def set_finding_state( - self, - ) -> Callable[ - [securitycenter_service.SetFindingStateRequest], Awaitable[finding.Finding] - ]: - r"""Return a callable for the set finding state method over gRPC. - - Updates the state of a finding. - - Returns: - Callable[[~.SetFindingStateRequest], - Awaitable[~.Finding]]: - 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 "set_finding_state" not in self._stubs: - self._stubs["set_finding_state"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/SetFindingState", - request_serializer=securitycenter_service.SetFindingStateRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs["set_finding_state"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], Awaitable[policy.Policy]]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets the access control policy on the specified - Source. - - Returns: - Callable[[~.SetIamPolicyRequest], - Awaitable[~.Policy]]: - 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 "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/SetIamPolicy", - request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], - Awaitable[iam_policy.TestIamPermissionsResponse], - ]: - r"""Return a callable for the test iam permissions method over gRPC. - - Returns the permissions that a caller has on the - specified source. - - Returns: - Callable[[~.TestIamPermissionsRequest], - Awaitable[~.TestIamPermissionsResponse]]: - 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 "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/TestIamPermissions", - request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - @property - def update_finding( - self, - ) -> Callable[ - [securitycenter_service.UpdateFindingRequest], Awaitable[gcs_finding.Finding] - ]: - r"""Return a callable for the update finding method over gRPC. - - Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Returns: - Callable[[~.UpdateFindingRequest], - Awaitable[~.Finding]]: - 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_finding" not in self._stubs: - self._stubs["update_finding"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateFinding", - request_serializer=securitycenter_service.UpdateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs["update_finding"] - - @property - def update_organization_settings( - self, - ) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - Awaitable[gcs_organization_settings.OrganizationSettings], - ]: - r"""Return a callable for the update organization settings method over gRPC. - - Updates an organization's settings. - - Returns: - Callable[[~.UpdateOrganizationSettingsRequest], - Awaitable[~.OrganizationSettings]]: - 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_organization_settings" not in self._stubs: - self._stubs["update_organization_settings"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateOrganizationSettings", - request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, - response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs["update_organization_settings"] - - @property - def update_source( - self, - ) -> Callable[ - [securitycenter_service.UpdateSourceRequest], Awaitable[gcs_source.Source] - ]: - r"""Return a callable for the update source method over gRPC. - - Updates a source. - - Returns: - Callable[[~.UpdateSourceRequest], - Awaitable[~.Source]]: - 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_source" not in self._stubs: - self._stubs["update_source"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSource", - request_serializer=securitycenter_service.UpdateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs["update_source"] - - @property - def update_security_marks( - self, - ) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - Awaitable[gcs_security_marks.SecurityMarks], - ]: - r"""Return a callable for the update security marks method over gRPC. - - Updates security marks. - - Returns: - Callable[[~.UpdateSecurityMarksRequest], - Awaitable[~.SecurityMarks]]: - 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_security_marks" not in self._stubs: - self._stubs["update_security_marks"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1beta1.SecurityCenter/UpdateSecurityMarks", - request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, - response_deserializer=gcs_security_marks.SecurityMarks.deserialize, - ) - return self._stubs["update_security_marks"] - - -__all__ = ("SecurityCenterGrpcAsyncIOTransport",) diff --git a/google/cloud/securitycenter_v1beta1/types/__init__.py b/google/cloud/securitycenter_v1beta1/types/__init__.py deleted file mode 100644 index 50ef54be..00000000 --- a/google/cloud/securitycenter_v1beta1/types/__init__.py +++ /dev/null @@ -1,77 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 .security_marks import SecurityMarks -from .asset import Asset -from .finding import Finding -from .organization_settings import OrganizationSettings -from .run_asset_discovery_response import RunAssetDiscoveryResponse -from .source import Source -from .securitycenter_service import ( - CreateFindingRequest, - CreateSourceRequest, - GetOrganizationSettingsRequest, - GetSourceRequest, - GroupAssetsRequest, - GroupAssetsResponse, - GroupFindingsRequest, - GroupFindingsResponse, - GroupResult, - ListSourcesRequest, - ListSourcesResponse, - ListAssetsRequest, - ListAssetsResponse, - ListFindingsRequest, - ListFindingsResponse, - SetFindingStateRequest, - RunAssetDiscoveryRequest, - UpdateFindingRequest, - UpdateOrganizationSettingsRequest, - UpdateSourceRequest, - UpdateSecurityMarksRequest, -) - - -__all__ = ( - "SecurityMarks", - "Asset", - "Finding", - "OrganizationSettings", - "RunAssetDiscoveryResponse", - "Source", - "CreateFindingRequest", - "CreateSourceRequest", - "GetOrganizationSettingsRequest", - "GetSourceRequest", - "GroupAssetsRequest", - "GroupAssetsResponse", - "GroupFindingsRequest", - "GroupFindingsResponse", - "GroupResult", - "ListSourcesRequest", - "ListSourcesResponse", - "ListAssetsRequest", - "ListAssetsResponse", - "ListFindingsRequest", - "ListFindingsResponse", - "SetFindingStateRequest", - "RunAssetDiscoveryRequest", - "UpdateFindingRequest", - "UpdateOrganizationSettingsRequest", - "UpdateSourceRequest", - "UpdateSecurityMarksRequest", -) diff --git a/google/cloud/securitycenter_v1beta1/types/asset.py b/google/cloud/securitycenter_v1beta1/types/asset.py deleted file mode 100644 index 80b4082d..00000000 --- a/google/cloud/securitycenter_v1beta1/types/asset.py +++ /dev/null @@ -1,129 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 proto # type: ignore - - -from google.cloud.securitycenter_v1beta1.types import ( - security_marks as gcs_security_marks, -) -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - - -__protobuf__ = proto.module( - package="google.cloud.securitycenter.v1beta1", manifest={"Asset",}, -) - - -class Asset(proto.Message): - r"""Security Command Center representation of a Google Cloud - resource. - - The Asset is a Security Command Center resource that captures - information about a single Google Cloud resource. All - modifications to an Asset are only within the context of - Security Command Center and don't affect the referenced Google - Cloud resource. - - Attributes: - name (str): - The relative resource name of this asset. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/assets/{asset_id}". - security_center_properties (~.asset.Asset.SecurityCenterProperties): - Security Command Center managed properties. - These properties are managed by Security Command - Center and cannot be modified by the user. - resource_properties (Sequence[~.asset.Asset.ResourcePropertiesEntry]): - Resource managed properties. These properties - are managed and defined by the Google Cloud - resource and cannot be modified by the user. - security_marks (~.gcs_security_marks.SecurityMarks): - User specified security marks. These marks - are entirely managed by the user and come from - the SecurityMarks resource that belongs to the - asset. - create_time (~.timestamp.Timestamp): - The time at which the asset was created in - Security Command Center. - update_time (~.timestamp.Timestamp): - The time at which the asset was last updated, - added, or deleted in Security Command Center. - """ - - class SecurityCenterProperties(proto.Message): - r"""Security Command Center managed properties. These properties - are managed by Security Command Center and cannot be modified by - the user. - - Attributes: - resource_name (str): - Immutable. The full resource name of the Google Cloud - resource this asset represents. This field is immutable - after create time. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_type (str): - The type of the Google Cloud resource. - Examples include: APPLICATION, PROJECT, and - ORGANIZATION. This is a case insensitive field - defined by Security Command Center and/or the - producer of the resource and is immutable after - create time. - resource_parent (str): - The full resource name of the immediate parent of the - resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_project (str): - The full resource name of the project the resource belongs - to. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_owners (Sequence[str]): - Owners of the Google Cloud resource. - """ - - resource_name = proto.Field(proto.STRING, number=1) - - resource_type = proto.Field(proto.STRING, number=2) - - resource_parent = proto.Field(proto.STRING, number=3) - - resource_project = proto.Field(proto.STRING, number=4) - - resource_owners = proto.RepeatedField(proto.STRING, number=5) - - name = proto.Field(proto.STRING, number=1) - - security_center_properties = proto.Field( - proto.MESSAGE, number=2, message=SecurityCenterProperties, - ) - - resource_properties = proto.MapField( - proto.STRING, proto.MESSAGE, number=7, message=struct.Value, - ) - - security_marks = proto.Field( - proto.MESSAGE, number=8, message=gcs_security_marks.SecurityMarks, - ) - - create_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) - - update_time = proto.Field(proto.MESSAGE, number=10, message=timestamp.Timestamp,) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1beta1/types/finding.py b/google/cloud/securitycenter_v1beta1/types/finding.py deleted file mode 100644 index 847a4f8e..00000000 --- a/google/cloud/securitycenter_v1beta1/types/finding.py +++ /dev/null @@ -1,125 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 proto # type: ignore - - -from google.cloud.securitycenter_v1beta1.types import ( - security_marks as gcs_security_marks, -) -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - - -__protobuf__ = proto.module( - package="google.cloud.securitycenter.v1beta1", manifest={"Finding",}, -) - - -class Finding(proto.Message): - r"""Security Command Center finding. - A finding is a record of assessment data (security, risk, health - or privacy) ingested into Security Command Center for - presentation, notification, analysis, policy testing, and - enforcement. For example, an XSS vulnerability in an App Engine - application is a finding. - - Attributes: - name (str): - The relative resource name of this finding. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}". - parent (str): - Immutable. The relative resource name of the source the - finding belongs to. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - This field is immutable after creation time. For example: - "organizations/{organization_id}/sources/{source_id}". - resource_name (str): - For findings on Google Cloud resources, the full resource - name of the Google Cloud resource this finding is for. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - When the finding is for a non-Google Cloud resource, the - resourceName can be a customer or partner defined string. - This field is immutable after creation time. - state (~.finding.Finding.State): - The state of the finding. - category (str): - The additional taxonomy group within findings from a given - source. This field is immutable after creation time. - Example: "XSS_FLASH_INJECTION". - external_uri (str): - The URI that, if available, points to a web - page outside of Security Command Center where - additional information about the finding can be - found. This field is guaranteed to be either - empty or a well formed URL. - source_properties (Sequence[~.finding.Finding.SourcePropertiesEntry]): - Source specific properties. These properties are managed by - the source that writes the finding. The key names in the - source_properties map must be between 1 and 255 characters, - and must start with a letter and contain alphanumeric - characters or underscores only. - security_marks (~.gcs_security_marks.SecurityMarks): - Output only. User specified security marks. - These marks are entirely managed by the user and - come from the SecurityMarks resource that - belongs to the finding. - event_time (~.timestamp.Timestamp): - The time at which the event took place. For - example, if the finding represents an open - firewall it would capture the time the detector - believes the firewall became open. The accuracy - is determined by the detector. - create_time (~.timestamp.Timestamp): - The time at which the finding was created in - Security Command Center. - """ - - class State(proto.Enum): - r"""The state of the finding.""" - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - INACTIVE = 2 - - name = proto.Field(proto.STRING, number=1) - - parent = proto.Field(proto.STRING, number=2) - - resource_name = proto.Field(proto.STRING, number=3) - - state = proto.Field(proto.ENUM, number=4, enum=State,) - - category = proto.Field(proto.STRING, number=5) - - external_uri = proto.Field(proto.STRING, number=6) - - source_properties = proto.MapField( - proto.STRING, proto.MESSAGE, number=7, message=struct.Value, - ) - - security_marks = proto.Field( - proto.MESSAGE, number=8, message=gcs_security_marks.SecurityMarks, - ) - - event_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) - - create_time = proto.Field(proto.MESSAGE, number=10, message=timestamp.Timestamp,) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1beta1/types/organization_settings.py b/google/cloud/securitycenter_v1beta1/types/organization_settings.py deleted file mode 100644 index 3b3ae0b1..00000000 --- a/google/cloud/securitycenter_v1beta1/types/organization_settings.py +++ /dev/null @@ -1,89 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 proto # type: ignore - - -__protobuf__ = proto.module( - package="google.cloud.securitycenter.v1beta1", manifest={"OrganizationSettings",}, -) - - -class OrganizationSettings(proto.Message): - r"""User specified settings that are attached to the Security - Command Center organization. - - Attributes: - name (str): - The relative resource name of the settings. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/organizationSettings". - enable_asset_discovery (bool): - A flag that indicates if Asset Discovery should be enabled. - If the flag is set to ``true``, then discovery of assets - will occur. If it is set to \`false, all historical assets - will remain, but discovery of future assets will not occur. - asset_discovery_config (~.organization_settings.OrganizationSettings.AssetDiscoveryConfig): - The configuration used for Asset Discovery - runs. - """ - - class AssetDiscoveryConfig(proto.Message): - r"""The configuration used for Asset Discovery runs. - - Attributes: - project_ids (Sequence[str]): - The project ids to use for filtering asset - discovery. - inclusion_mode (~.organization_settings.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): - The mode to use for filtering asset - discovery. - """ - - class InclusionMode(proto.Enum): - r"""The mode of inclusion when running Asset Discovery. Asset discovery - can be limited by explicitly identifying projects to be included or - excluded. If INCLUDE_ONLY is set, then only those projects within - the organization and their children are discovered during asset - discovery. If EXCLUDE is set, then projects that don't match those - projects are discovered during asset discovery. If neither are set, - then all projects within the organization are discovered during - asset discovery. - """ - INCLUSION_MODE_UNSPECIFIED = 0 - INCLUDE_ONLY = 1 - EXCLUDE = 2 - - project_ids = proto.RepeatedField(proto.STRING, number=1) - - inclusion_mode = proto.Field( - proto.ENUM, - number=2, - enum="OrganizationSettings.AssetDiscoveryConfig.InclusionMode", - ) - - name = proto.Field(proto.STRING, number=1) - - enable_asset_discovery = proto.Field(proto.BOOL, number=2) - - asset_discovery_config = proto.Field( - proto.MESSAGE, number=3, message=AssetDiscoveryConfig, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py b/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py deleted file mode 100644 index 0b9e9d95..00000000 --- a/google/cloud/securitycenter_v1beta1/types/run_asset_discovery_response.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 proto # type: ignore - - -from google.protobuf import duration_pb2 as gp_duration # type: ignore - - -__protobuf__ = proto.module( - package="google.cloud.securitycenter.v1beta1", - manifest={"RunAssetDiscoveryResponse",}, -) - - -class RunAssetDiscoveryResponse(proto.Message): - r"""Response of asset discovery run - - Attributes: - state (~.run_asset_discovery_response.RunAssetDiscoveryResponse.State): - The state of an asset discovery run. - duration (~.gp_duration.Duration): - The duration between asset discovery run - start and end - """ - - class State(proto.Enum): - r"""The state of an asset discovery run.""" - STATE_UNSPECIFIED = 0 - COMPLETED = 1 - SUPERSEDED = 2 - TERMINATED = 3 - - state = proto.Field(proto.ENUM, number=1, enum=State,) - - duration = proto.Field(proto.MESSAGE, number=2, message=gp_duration.Duration,) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1beta1/types/security_marks.py b/google/cloud/securitycenter_v1beta1/types/security_marks.py deleted file mode 100644 index 7964b095..00000000 --- a/google/cloud/securitycenter_v1beta1/types/security_marks.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 proto # type: ignore - - -__protobuf__ = proto.module( - package="google.cloud.securitycenter.v1beta1", manifest={"SecurityMarks",}, -) - - -class SecurityMarks(proto.Message): - r"""User specified security marks that are attached to the parent - Security Command Center resource. Security marks are scoped - within a Security Command Center organization -- they can be - modified and viewed by all users who have proper permissions on - the organization. - - Attributes: - name (str): - The relative resource name of the SecurityMarks. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Examples: - "organizations/{organization_id}/assets/{asset_id}/securityMarks" - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks". - marks (Sequence[~.security_marks.SecurityMarks.MarksEntry]): - Mutable user specified security marks belonging to the - parent resource. Constraints are as follows: - - - Keys and values are treated as case insensitive - - Keys must be between 1 - 256 characters (inclusive) - - Keys must be letters, numbers, underscores, or dashes - - Values have leading and trailing whitespace trimmed, - remaining characters must be between 1 - 4096 characters - (inclusive) - """ - - name = proto.Field(proto.STRING, number=1) - - marks = proto.MapField(proto.STRING, proto.STRING, number=2) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py b/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py deleted file mode 100644 index 833f60fc..00000000 --- a/google/cloud/securitycenter_v1beta1/types/securitycenter_service.py +++ /dev/null @@ -1,862 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 proto # type: ignore - - -from google.cloud.securitycenter_v1beta1.types import asset as gcs_asset -from google.cloud.securitycenter_v1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1beta1.types import ( - organization_settings as gcs_organization_settings, -) -from google.cloud.securitycenter_v1beta1.types import ( - security_marks as gcs_security_marks, -) -from google.cloud.securitycenter_v1beta1.types import source as gcs_source -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as gp_field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - - -__protobuf__ = proto.module( - package="google.cloud.securitycenter.v1beta1", - manifest={ - "CreateFindingRequest", - "CreateSourceRequest", - "GetOrganizationSettingsRequest", - "GetSourceRequest", - "GroupAssetsRequest", - "GroupAssetsResponse", - "GroupFindingsRequest", - "GroupFindingsResponse", - "GroupResult", - "ListSourcesRequest", - "ListSourcesResponse", - "ListAssetsRequest", - "ListAssetsResponse", - "ListFindingsRequest", - "ListFindingsResponse", - "SetFindingStateRequest", - "RunAssetDiscoveryRequest", - "UpdateFindingRequest", - "UpdateOrganizationSettingsRequest", - "UpdateSourceRequest", - "UpdateSecurityMarksRequest", - }, -) - - -class CreateFindingRequest(proto.Message): - r"""Request message for creating a finding. - - Attributes: - parent (str): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - finding_id (str): - Required. Unique identifier provided by the - client within the parent scope. It must be - alphanumeric and less than or equal to 32 - characters and greater than 0 characters in - length. - finding (~.gcs_finding.Finding): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output only - fields on this resource. - """ - - parent = proto.Field(proto.STRING, number=1) - - finding_id = proto.Field(proto.STRING, number=2) - - finding = proto.Field(proto.MESSAGE, number=3, message=gcs_finding.Finding,) - - -class CreateSourceRequest(proto.Message): - r"""Request message for creating a source. - - Attributes: - parent (str): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - source (~.gcs_source.Source): - Required. The Source being created, only the display_name - and description will be used. All other fields will be - ignored. - """ - - parent = proto.Field(proto.STRING, number=1) - - source = proto.Field(proto.MESSAGE, number=2, message=gcs_source.Source,) - - -class GetOrganizationSettingsRequest(proto.Message): - r"""Request message for getting organization settings. - - Attributes: - name (str): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - """ - - name = proto.Field(proto.STRING, number=1) - - -class GetSourceRequest(proto.Message): - r"""Request message for getting a source. - - Attributes: - name (str): - Required. Relative resource name of the source. Its format - is "organizations/[organization_id]/source/[source_id]". - """ - - name = proto.Field(proto.STRING, number=1) - - -class GroupAssetsRequest(proto.Message): - r"""Request message for grouping by assets. - - Attributes: - parent (str): - Required. Name of the organization to groupBy. Its format is - "organizations/[organization_id]". - filter (str): - Expression that defines the filter to apply across assets. - The expression is a list of zero or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are not supported, and ``OR`` has higher - precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the Asset - resource. Examples include: - - - name - - security_center_properties.resource_name - - resource_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - For example, ``resource_properties.size = 100`` is a valid - filter string. - group_by (str): - Required. Expression that defines what assets fields to use - for grouping. The string value should follow SQL syntax: - comma separated list of fields. For example: - "security_center_properties.resource_project,security_center_properties.project". - - The following fields are supported when compare_duration is - not set: - - - security_center_properties.resource_project - - security_center_properties.resource_type - - security_center_properties.resource_parent - - The following fields are supported when compare_duration is - set: - - - security_center_properties.resource_type - compare_duration (~.duration.Duration): - When compare_duration is set, the Asset's "state" property - is updated to indicate whether the asset was added, removed, - or remained present during the compare_duration period of - time that precedes the read_time. This is the time between - (read_time - compare_duration) and read_time. - - The state value is derived based on the presence of the - asset at the two points in time. Intermediate state changes - between the two times don't affect the result. For example, - the results aren't affected if the asset is removed and - re-created again. - - Possible "state" values when compare_duration is specified: - - - "ADDED": indicates that the asset was not present before - compare_duration, but present at reference_time. - - "REMOVED": indicates that the asset was present at the - start of compare_duration, but not present at - reference_time. - - "ACTIVE": indicates that the asset was present at both - the start and the end of the time period defined by - compare_duration and reference_time. - - This field is ignored if ``state`` is not a field in - ``group_by``. - read_time (~.timestamp.Timestamp): - Time used as a reference point when filtering - assets. The filter is limited to assets existing - at the supplied time and their values are those - at that specific time. Absence of this field - will default to the API's version of NOW. - page_token (str): - The value returned by the last ``GroupAssetsResponse``; - indicates that this is a continuation of a prior - ``GroupAssets`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - group_by = proto.Field(proto.STRING, number=3) - - compare_duration = proto.Field(proto.MESSAGE, number=4, message=duration.Duration,) - - read_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) - - page_token = proto.Field(proto.STRING, number=7) - - page_size = proto.Field(proto.INT32, number=8) - - -class GroupAssetsResponse(proto.Message): - r"""Response message for grouping by assets. - - Attributes: - group_by_results (Sequence[~.securitycenter_service.GroupResult]): - Group results. There exists an element for - each existing unique combination of - property/values. The element contains a count - for the number of times those specific - property/values appear. - read_time (~.timestamp.Timestamp): - Time used for executing the groupBy request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - group_by_results = proto.RepeatedField( - proto.MESSAGE, number=1, message="GroupResult", - ) - - read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - next_page_token = proto.Field(proto.STRING, number=3) - - -class GroupFindingsRequest(proto.Message): - r"""Request message for grouping by findings. - - Attributes: - parent (str): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]". To - groupBy across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/- - filter (str): - Expression that defines the filter to apply across findings. - The expression is a list of one or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are not supported, and ``OR`` has higher - precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. Examples include: - - - name - - source_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - For example, ``source_properties.size = 100`` is a valid - filter string. - group_by (str): - Required. Expression that defines what assets fields to use - for grouping (including ``state``). The string value should - follow SQL syntax: comma separated list of fields. For - example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - read_time (~.timestamp.Timestamp): - Time used as a reference point when filtering - findings. The filter is limited to findings - existing at the supplied time and their values - are those at that specific time. Absence of this - field will default to the API's version of NOW. - page_token (str): - The value returned by the last ``GroupFindingsResponse``; - indicates that this is a continuation of a prior - ``GroupFindings`` call, and that the system should return - the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - group_by = proto.Field(proto.STRING, number=3) - - read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) - - page_token = proto.Field(proto.STRING, number=5) - - page_size = proto.Field(proto.INT32, number=6) - - -class GroupFindingsResponse(proto.Message): - r"""Response message for group by findings. - - Attributes: - group_by_results (Sequence[~.securitycenter_service.GroupResult]): - Group results. There exists an element for - each existing unique combination of - property/values. The element contains a count - for the number of times those specific - property/values appear. - read_time (~.timestamp.Timestamp): - Time used for executing the groupBy request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - group_by_results = proto.RepeatedField( - proto.MESSAGE, number=1, message="GroupResult", - ) - - read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - next_page_token = proto.Field(proto.STRING, number=3) - - -class GroupResult(proto.Message): - r"""Result containing the properties and count of a groupBy - request. - - Attributes: - properties (Sequence[~.securitycenter_service.GroupResult.PropertiesEntry]): - Properties matching the groupBy fields in the - request. - count (int): - Total count of resources for the given - properties. - """ - - properties = proto.MapField( - proto.STRING, proto.MESSAGE, number=1, message=struct.Value, - ) - - count = proto.Field(proto.INT64, number=2) - - -class ListSourcesRequest(proto.Message): - r"""Request message for listing sources. - - Attributes: - parent (str): - Required. Resource name of the parent of sources to list. - Its format should be "organizations/[organization_id]". - page_token (str): - The value returned by the last ``ListSourcesResponse``; - indicates that this is a continuation of a prior - ``ListSources`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field(proto.STRING, number=1) - - page_token = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=7) - - -class ListSourcesResponse(proto.Message): - r"""Response message for listing sources. - - Attributes: - sources (Sequence[~.gcs_source.Source]): - Sources belonging to the requested parent. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - sources = proto.RepeatedField(proto.MESSAGE, number=1, message=gcs_source.Source,) - - next_page_token = proto.Field(proto.STRING, number=2) - - -class ListAssetsRequest(proto.Message): - r"""Request message for listing assets. - - Attributes: - parent (str): - Required. Name of the organization assets should belong to. - Its format is "organizations/[organization_id]". - filter (str): - Expression that defines the filter to apply across assets. - The expression is a list of zero or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are not supported, and ``OR`` has higher - precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the Asset - resource. Examples include: - - - name - - security_center_properties.resource_name - - resource_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - For example, ``resource_properties.size = 100`` is a valid - filter string. - order_by (str): - Expression that defines what fields and order to use for - sorting. The string value should follow SQL syntax: comma - separated list of fields. For example: - "name,resource_properties.a_property". The default sorting - order is ascending. To specify descending order for a field, - a suffix " desc" should be appended to the field name. For - example: "name desc,resource_properties.a_property". - Redundant space characters in the syntax are insignificant. - "name desc,resource_properties.a_property" and " name desc , - resource_properties.a_property " are equivalent. - read_time (~.timestamp.Timestamp): - Time used as a reference point when filtering - assets. The filter is limited to assets existing - at the supplied time and their values are those - at that specific time. Absence of this field - will default to the API's version of NOW. - compare_duration (~.duration.Duration): - When compare_duration is set, the ListAssetResult's "state" - attribute is updated to indicate whether the asset was - added, removed, or remained present during the - compare_duration period of time that precedes the read_time. - This is the time between (read_time - compare_duration) and - read_time. - - The state value is derived based on the presence of the - asset at the two points in time. Intermediate state changes - between the two times don't affect the result. For example, - the results aren't affected if the asset is removed and - re-created again. - - Possible "state" values when compare_duration is specified: - - - "ADDED": indicates that the asset was not present before - compare_duration, but present at read_time. - - "REMOVED": indicates that the asset was present at the - start of compare_duration, but not present at read_time. - - "ACTIVE": indicates that the asset was present at both - the start and the end of the time period defined by - compare_duration and read_time. - - If compare_duration is not specified, then the only possible - state is "UNUSED", which indicates that the asset is present - at read_time. - field_mask (~.gp_field_mask.FieldMask): - Optional. A field mask to specify the - ListAssetsResult fields to be listed in the - response. An empty field mask will list all - fields. - page_token (str): - The value returned by the last ``ListAssetsResponse``; - indicates that this is a continuation of a prior - ``ListAssets`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - order_by = proto.Field(proto.STRING, number=3) - - read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) - - compare_duration = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) - - field_mask = proto.Field(proto.MESSAGE, number=7, message=gp_field_mask.FieldMask,) - - page_token = proto.Field(proto.STRING, number=8) - - page_size = proto.Field(proto.INT32, number=9) - - -class ListAssetsResponse(proto.Message): - r"""Response message for listing assets. - - Attributes: - list_assets_results (Sequence[~.securitycenter_service.ListAssetsResponse.ListAssetsResult]): - Assets matching the list request. - read_time (~.timestamp.Timestamp): - Time used for executing the list request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of assets matching the - query. - """ - - class ListAssetsResult(proto.Message): - r"""Result containing the Asset and its State. - - Attributes: - asset (~.gcs_asset.Asset): - Asset matching the search request. - state (~.securitycenter_service.ListAssetsResponse.ListAssetsResult.State): - State of the asset. - """ - - class State(proto.Enum): - r"""State of the asset. - - When querying across two points in time this describes the change - between the two points: ADDED, REMOVED, or ACTIVE. If there was no - compare_duration supplied in the request the state should be: UNUSED - """ - STATE_UNSPECIFIED = 0 - UNUSED = 1 - ADDED = 2 - REMOVED = 3 - ACTIVE = 4 - - asset = proto.Field(proto.MESSAGE, number=1, message=gcs_asset.Asset,) - - state = proto.Field( - proto.ENUM, number=2, enum="ListAssetsResponse.ListAssetsResult.State", - ) - - @property - def raw_page(self): - return self - - list_assets_results = proto.RepeatedField( - proto.MESSAGE, number=1, message=ListAssetsResult, - ) - - read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - next_page_token = proto.Field(proto.STRING, number=3) - - total_size = proto.Field(proto.INT32, number=4) - - -class ListFindingsRequest(proto.Message): - r"""Request message for listing findings. - - Attributes: - parent (str): - Required. Name of the source the findings belong to. Its - format is - "organizations/[organization_id]/sources/[source_id]". To - list across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/- - filter (str): - Expression that defines the filter to apply across findings. - The expression is a list of one or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are not supported, and ``OR`` has higher - precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. Examples include: - - - name - - source_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - For example, ``source_properties.size = 100`` is a valid - filter string. - order_by (str): - Expression that defines what fields and order to use for - sorting. The string value should follow SQL syntax: comma - separated list of fields. For example: - "name,resource_properties.a_property". The default sorting - order is ascending. To specify descending order for a field, - a suffix " desc" should be appended to the field name. For - example: "name desc,source_properties.a_property". Redundant - space characters in the syntax are insignificant. "name - desc,source_properties.a_property" and " name desc , - source_properties.a_property " are equivalent. - read_time (~.timestamp.Timestamp): - Time used as a reference point when filtering - findings. The filter is limited to findings - existing at the supplied time and their values - are those at that specific time. Absence of this - field will default to the API's version of NOW. - field_mask (~.gp_field_mask.FieldMask): - Optional. A field mask to specify the Finding - fields to be listed in the response. An empty - field mask will list all fields. - page_token (str): - The value returned by the last ``ListFindingsResponse``; - indicates that this is a continuation of a prior - ``ListFindings`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - order_by = proto.Field(proto.STRING, number=3) - - read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) - - field_mask = proto.Field(proto.MESSAGE, number=5, message=gp_field_mask.FieldMask,) - - page_token = proto.Field(proto.STRING, number=6) - - page_size = proto.Field(proto.INT32, number=7) - - -class ListFindingsResponse(proto.Message): - r"""Response message for listing findings. - - Attributes: - findings (Sequence[~.gcs_finding.Finding]): - Findings matching the list request. - read_time (~.timestamp.Timestamp): - Time used for executing the list request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of findings matching the - query. - """ - - @property - def raw_page(self): - return self - - findings = proto.RepeatedField( - proto.MESSAGE, number=1, message=gcs_finding.Finding, - ) - - read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - next_page_token = proto.Field(proto.STRING, number=3) - - total_size = proto.Field(proto.INT32, number=4) - - -class SetFindingStateRequest(proto.Message): - r"""Request message for updating a finding's state. - - Attributes: - name (str): - Required. The relative resource name of the finding. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - state (~.gcs_finding.Finding.State): - Required. The desired State of the finding. - start_time (~.timestamp.Timestamp): - Required. The time at which the updated state - takes effect. - """ - - name = proto.Field(proto.STRING, number=1) - - state = proto.Field(proto.ENUM, number=2, enum=gcs_finding.Finding.State,) - - start_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) - - -class RunAssetDiscoveryRequest(proto.Message): - r"""Request message for running asset discovery for an - organization. - - Attributes: - parent (str): - Required. Name of the organization to run asset discovery - for. Its format is "organizations/[organization_id]". - """ - - parent = proto.Field(proto.STRING, number=1) - - -class UpdateFindingRequest(proto.Message): - r"""Request message for updating or creating a finding. - - Attributes: - finding (~.gcs_finding.Finding): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the name - must alphanumeric and less than or equal to 32 characters - and greater than 0 characters in length. - update_mask (~.gp_field_mask.FieldMask): - The FieldMask to use when updating the - finding resource. This field should not be - specified when creating a finding. - """ - - finding = proto.Field(proto.MESSAGE, number=1, message=gcs_finding.Finding,) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) - - -class UpdateOrganizationSettingsRequest(proto.Message): - r"""Request message for updating an organization's settings. - - Attributes: - organization_settings (~.gcs_organization_settings.OrganizationSettings): - Required. The organization settings resource - to update. - update_mask (~.gp_field_mask.FieldMask): - The FieldMask to use when updating the - settings resource. - """ - - organization_settings = proto.Field( - proto.MESSAGE, number=1, message=gcs_organization_settings.OrganizationSettings, - ) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) - - -class UpdateSourceRequest(proto.Message): - r"""Request message for updating a source. - - Attributes: - source (~.gcs_source.Source): - Required. The source resource to update. - update_mask (~.gp_field_mask.FieldMask): - The FieldMask to use when updating the source - resource. - """ - - source = proto.Field(proto.MESSAGE, number=1, message=gcs_source.Source,) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) - - -class UpdateSecurityMarksRequest(proto.Message): - r"""Request message for updating a SecurityMarks resource. - - Attributes: - security_marks (~.gcs_security_marks.SecurityMarks): - Required. The security marks resource to - update. - update_mask (~.gp_field_mask.FieldMask): - The FieldMask to use when updating the - security marks resource. - start_time (~.timestamp.Timestamp): - The time at which the updated SecurityMarks - take effect. - """ - - security_marks = proto.Field( - proto.MESSAGE, number=1, message=gcs_security_marks.SecurityMarks, - ) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) - - start_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1beta1/types/source.py b/google/cloud/securitycenter_v1beta1/types/source.py deleted file mode 100644 index 2546454f..00000000 --- a/google/cloud/securitycenter_v1beta1/types/source.py +++ /dev/null @@ -1,64 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 proto # type: ignore - - -__protobuf__ = proto.module( - package="google.cloud.securitycenter.v1beta1", manifest={"Source",}, -) - - -class Source(proto.Message): - r"""Security Command Center finding source. A finding source - is an entity or a mechanism that can produce a finding. A source - is like a container of findings that come from the same scanner, - logger, monitor, etc. - - Attributes: - name (str): - The relative resource name of this source. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}". - display_name (str): - The source's display name. - A source's display name must be unique amongst - its siblings, for example, two sources with the - same parent can't share the same display name. - The display name must have a length between 1 - and 64 characters (inclusive). - description (str): - The description of the source (max of 1024 - characters). Example: - "Web Security Scanner is a web security scanner - for common vulnerabilities in App Engine - applications. It can automatically scan and - detect four common vulnerabilities, including - cross-site-scripting (XSS), Flash injection, - mixed content (HTTP in HTTPS), and - outdated/insecure libraries.". - """ - - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - description = proto.Field(proto.STRING, number=3) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/py.typed b/google/cloud/securitycenter_v1p1beta1/py.typed deleted file mode 100644 index 23a44fc7..00000000 --- a/google/cloud/securitycenter_v1p1beta1/py.typed +++ /dev/null @@ -1,2 +0,0 @@ -# Marker file for PEP 561. -# The google-cloud-securitycenter package uses inline types. diff --git a/google/cloud/securitycenter_v1p1beta1/services/__init__.py b/google/cloud/securitycenter_v1p1beta1/services/__init__.py deleted file mode 100644 index 42ffdf2b..00000000 --- a/google/cloud/securitycenter_v1p1beta1/services/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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. -# diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py deleted file mode 100644 index 6250349b..00000000 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 SecurityCenterClient -from .async_client import SecurityCenterAsyncClient - -__all__ = ( - "SecurityCenterClient", - "SecurityCenterAsyncClient", -) diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py deleted file mode 100644 index 31718663..00000000 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/async_client.py +++ /dev/null @@ -1,2317 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 -import functools -import re -from typing import Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation -from google.api_core import operation_async -from google.cloud.securitycenter_v1p1beta1.services.security_center import pagers -from google.cloud.securitycenter_v1p1beta1.types import finding -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import ( - notification_config as gcs_notification_config, -) -from google.cloud.securitycenter_v1p1beta1.types import organization_settings -from google.cloud.securitycenter_v1p1beta1.types import ( - organization_settings as gcs_organization_settings, -) -from google.cloud.securitycenter_v1p1beta1.types import run_asset_discovery_response -from google.cloud.securitycenter_v1p1beta1.types import security_marks -from google.cloud.securitycenter_v1p1beta1.types import ( - security_marks as gcs_security_marks, -) -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - -from .transports.base import SecurityCenterTransport -from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport -from .client import SecurityCenterClient - - -class SecurityCenterAsyncClient: - """V1p1Beta1 APIs for Security Center service.""" - - _client: SecurityCenterClient - - DEFAULT_ENDPOINT = SecurityCenterClient.DEFAULT_ENDPOINT - DEFAULT_MTLS_ENDPOINT = SecurityCenterClient.DEFAULT_MTLS_ENDPOINT - - organization_settings_path = staticmethod( - SecurityCenterClient.organization_settings_path - ) - - security_marks_path = staticmethod(SecurityCenterClient.security_marks_path) - - finding_path = staticmethod(SecurityCenterClient.finding_path) - - source_path = staticmethod(SecurityCenterClient.source_path) - - notification_config_path = staticmethod( - SecurityCenterClient.notification_config_path - ) - - from_service_account_file = SecurityCenterClient.from_service_account_file - from_service_account_json = from_service_account_file - - get_transport_class = functools.partial( - type(SecurityCenterClient).get_transport_class, type(SecurityCenterClient) - ) - - def __init__( - self, - *, - credentials: credentials.Credentials = None, - transport: Union[str, SecurityCenterTransport] = "grpc_asyncio", - client_options: ClientOptions = None, - ) -> None: - """Instantiate the security center 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. - transport (Union[str, ~.SecurityCenterTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint, this is the default value for - the environment variable) and "auto" (auto switch to the default - mTLS endpoint if client SSL credentials is present). However, - the ``api_endpoint`` property takes precedence if provided. - (2) The ``client_cert_source`` property is used to provide client - SSL credentials for mutual TLS transport. If not provided, the - default SSL credentials will be used if present. - - Raises: - google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport - creation failed for any reason. - """ - - self._client = SecurityCenterClient( - credentials=credentials, transport=transport, client_options=client_options, - ) - - async def create_source( - self, - request: securitycenter_service.CreateSourceRequest = None, - *, - parent: str = None, - source: gcs_source.Source = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Creates a source. - - Args: - request (:class:`~.securitycenter_service.CreateSourceRequest`): - The request object. Request message for creating a - source. - parent (:class:`str`): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (:class:`~.gcs_source.Source`): - Required. The Source being created, only the - display_name and description will be used. All other - fields will be ignored. - This corresponds to the ``source`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([parent, source]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.CreateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_source, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def create_finding( - self, - request: securitycenter_service.CreateFindingRequest = None, - *, - parent: str = None, - finding_id: str = None, - finding: gcs_finding.Finding = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Args: - request (:class:`~.securitycenter_service.CreateFindingRequest`): - The request object. Request message for creating a - finding. - parent (:class:`str`): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding_id (:class:`str`): - Required. Unique identifier provided - by the client within the parent scope. - It must be alphanumeric and less than or - equal to 32 characters and greater than - 0 characters in length. - This corresponds to the ``finding_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding (:class:`~.gcs_finding.Finding`): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output - only fields on this resource. - This corresponds to the ``finding`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_finding.Finding: - Security Command Center finding. - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([parent, finding_id, finding]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.CreateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if finding_id is not None: - request.finding_id = finding_id - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_finding, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def create_notification_config( - self, - request: securitycenter_service.CreateNotificationConfigRequest = None, - *, - parent: str = None, - config_id: str = None, - notification_config: gcs_notification_config.NotificationConfig = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Creates a notification config. - - Args: - request (:class:`~.securitycenter_service.CreateNotificationConfigRequest`): - The request object. Request message for creating a - notification config. - parent (:class:`str`): - Required. Resource name of the new notification config's - parent. Its format is "organizations/[organization_id]". - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - config_id (:class:`str`): - Required. - Unique identifier provided by the client - within the parent scope. It must be - between 1 and 128 characters, and - contains alphanumeric characters, - underscores or hyphens only. - This corresponds to the ``config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - notification_config (:class:`~.gcs_notification_config.NotificationConfig`): - Required. The notification config - being created. The name and the service - account will be ignored as they are both - output only fields on this resource. - This corresponds to the ``notification_config`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_notification_config.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([parent, config_id, notification_config]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.CreateNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if config_id is not None: - request.config_id = config_id - if notification_config is not None: - request.notification_config = notification_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.create_notification_config, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def delete_notification_config( - self, - request: securitycenter_service.DeleteNotificationConfigRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a notification config. - - Args: - request (:class:`~.securitycenter_service.DeleteNotificationConfigRequest`): - The request object. Request message for deleting a - notification config. - name (:class:`str`): - Required. Name of the notification config to delete. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_id]". - This corresponds to the ``name`` 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([name]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.DeleteNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.delete_notification_config, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - await rpc( - request, retry=retry, timeout=timeout, metadata=metadata, - ) - - async def get_iam_policy( - self, - request: iam_policy.GetIamPolicyRequest = None, - *, - resource: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: - r"""Gets the access control policy on the specified - Source. - - Args: - request (:class:`~.iam_policy.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - This corresponds to the ``resource`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([resource]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.GetIamPolicyRequest(**request) - - elif not request: - request = iam_policy.GetIamPolicyRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_iam_policy, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_notification_config( - self, - request: securitycenter_service.GetNotificationConfigRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> notification_config.NotificationConfig: - r"""Gets a notification config. - - Args: - request (:class:`~.securitycenter_service.GetNotificationConfigRequest`): - The request object. Request message for getting a - notification config. - name (:class:`str`): - Required. Name of the notification config to get. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_id]". - This corresponds to the ``name`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.notification_config.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([name]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.GetNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_notification_config, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_organization_settings( - self, - request: securitycenter_service.GetOrganizationSettingsRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> organization_settings.OrganizationSettings: - r"""Gets the settings for an organization. - - Args: - request (:class:`~.securitycenter_service.GetOrganizationSettingsRequest`): - The request object. Request message for getting - organization settings. - name (:class:`str`): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - This corresponds to the ``name`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.organization_settings.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([name]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.GetOrganizationSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_organization_settings, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def get_source( - self, - request: securitycenter_service.GetSourceRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> source.Source: - r"""Gets a source. - - Args: - request (:class:`~.securitycenter_service.GetSourceRequest`): - The request object. Request message for getting a - source. - name (:class:`str`): - Required. Relative resource name of the source. Its - format is - "organizations/[organization_id]/source/[source_id]". - This corresponds to the ``name`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([name]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.GetSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.get_source, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def group_assets( - self, - request: securitycenter_service.GroupAssetsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupAssetsAsyncPager: - r"""Filters an organization's assets and groups them by - their specified properties. - - Args: - request (:class:`~.securitycenter_service.GroupAssetsRequest`): - The request object. Request message for grouping by - assets. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.GroupAssetsAsyncPager: - Response message for grouping by - assets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - - request = securitycenter_service.GroupAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.group_assets, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.GroupAssetsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - async def group_findings( - self, - request: securitycenter_service.GroupFindingsRequest = None, - *, - parent: str = None, - group_by: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupFindingsAsyncPager: - r"""Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: - /v1p1beta1/organizations/{organization_id}/sources/-/findings - - Args: - request (:class:`~.securitycenter_service.GroupFindingsRequest`): - The request object. Request message for grouping by - findings. - parent (:class:`str`): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]". - To groupBy across all sources provide a source_id of - ``-``. For example: - organizations/{organization_id}/sources/- - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - group_by (:class:`str`): - Required. Expression that defines what assets fields to - use for grouping (including ``state_change``). The - string value should follow SQL syntax: comma separated - list of fields. For example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - - The following fields are supported when compare_duration - is set: - - - state_change - This corresponds to the ``group_by`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.GroupFindingsAsyncPager: - Response message for group by - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([parent, group_by]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.GroupFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.group_findings, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.GroupFindingsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_assets( - self, - request: securitycenter_service.ListAssetsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAssetsAsyncPager: - r"""Lists an organization's assets. - - Args: - request (:class:`~.securitycenter_service.ListAssetsRequest`): - The request object. Request message for listing assets. - parent (:class:`str`): - Required. Name of the organization assets should belong - to. Its format is "organizations/[organization_id]". - This corresponds to the ``parent`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.ListAssetsAsyncPager: - Response message for listing assets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.ListAssetsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_assets, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListAssetsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_findings( - self, - request: securitycenter_service.ListFindingsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFindingsAsyncPager: - r"""Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1p1beta1/organizations/{organization_id}/sources/-/findings - - Args: - request (:class:`~.securitycenter_service.ListFindingsRequest`): - The request object. Request message for listing - findings. - parent (:class:`str`): - Required. Name of the source the findings belong to. Its - format is - "organizations/[organization_id]/sources/[source_id]". - To list across all sources provide a source_id of ``-``. - For example: organizations/{organization_id}/sources/- - This corresponds to the ``parent`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.ListFindingsAsyncPager: - Response message for listing - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.ListFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_findings, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListFindingsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_notification_configs( - self, - request: securitycenter_service.ListNotificationConfigsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListNotificationConfigsAsyncPager: - r"""Lists notification configs. - - Args: - request (:class:`~.securitycenter_service.ListNotificationConfigsRequest`): - The request object. Request message for listing - notification configs. - parent (:class:`str`): - Required. Name of the organization to list notification - configs. Its format is - "organizations/[organization_id]". - This corresponds to the ``parent`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.ListNotificationConfigsAsyncPager: - Response message for listing - notification configs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.ListNotificationConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_notification_configs, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListNotificationConfigsAsyncPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - async def list_sources( - self, - request: securitycenter_service.ListSourcesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSourcesAsyncPager: - r"""Lists all sources belonging to an organization. - - Args: - request (:class:`~.securitycenter_service.ListSourcesRequest`): - The request object. Request message for listing sources. - parent (:class:`str`): - Required. Resource name of the parent of sources to - list. Its format should be - "organizations/[organization_id]". - This corresponds to the ``parent`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.ListSourcesAsyncPager: - Response message for listing sources. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.ListSourcesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.list_sources, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__aiter__` convenience method. - response = pagers.ListSourcesAsyncPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - async def run_asset_discovery( - self, - request: securitycenter_service.RunAssetDiscoveryRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation_async.AsyncOperation: - r"""Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Args: - request (:class:`~.securitycenter_service.RunAssetDiscoveryRequest`): - The request object. Request message for running asset - discovery for an organization. - parent (:class:`str`): - Required. Name of the organization to run asset - discovery for. Its format is - "organizations/[organization_id]". - This corresponds to the ``parent`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operation_async.AsyncOperation: - An object representing a long-running operation. - - The result type for the operation will be - :class:``~.run_asset_discovery_response.RunAssetDiscoveryResponse``: - Response of asset discovery run - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([parent]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.RunAssetDiscoveryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.run_asset_discovery, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Wrap the response in an operation future. - response = operation_async.from_gapic( - response, - self._client._transport.operations_client, - run_asset_discovery_response.RunAssetDiscoveryResponse, - metadata_type=empty.Empty, - ) - - # Done; return the response. - return response - - async def set_finding_state( - self, - request: securitycenter_service.SetFindingStateRequest = None, - *, - name: str = None, - state: finding.Finding.State = None, - start_time: timestamp.Timestamp = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the state of a finding. - - Args: - request (:class:`~.securitycenter_service.SetFindingStateRequest`): - The request object. Request message for updating a - finding's state. - name (:class:`str`): - Required. The relative resource name of the finding. - See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - state (:class:`~.finding.Finding.State`): - Required. The desired State of the - finding. - This corresponds to the ``state`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - start_time (:class:`~.timestamp.Timestamp`): - Required. The time at which the - updated state takes effect. - This corresponds to the ``start_time`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.finding.Finding: - Security Command Center finding. - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([name, state, start_time]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.SetFindingStateRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - if state is not None: - request.state = state - if start_time is not None: - request.start_time = start_time - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_finding_state, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def set_iam_policy( - self, - request: iam_policy.SetIamPolicyRequest = None, - *, - resource: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: - r"""Sets the access control policy on the specified - Source. - - Args: - request (:class:`~.iam_policy.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - This corresponds to the ``resource`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([resource]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.SetIamPolicyRequest(**request) - - elif not request: - request = iam_policy.SetIamPolicyRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.set_iam_policy, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def test_iam_permissions( - self, - request: iam_policy.TestIamPermissionsRequest = None, - *, - resource: str = None, - permissions: Sequence[str] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: - r"""Returns the permissions that a caller has on the - specified source. - - Args: - request (:class:`~.iam_policy.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (:class:`Sequence[str]`): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - This corresponds to the ``permissions`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.iam_policy.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([resource, permissions]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.TestIamPermissionsRequest(**request) - - elif not request: - request = iam_policy.TestIamPermissionsRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource - - if permissions: - request.permissions.extend(permissions) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.test_iam_permissions, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def update_finding( - self, - request: securitycenter_service.UpdateFindingRequest = None, - *, - finding: gcs_finding.Finding = None, - update_mask: field_mask.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Args: - request (:class:`~.securitycenter_service.UpdateFindingRequest`): - The request object. Request message for updating or - creating a finding. - finding (:class:`~.gcs_finding.Finding`): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the - name must be alphanumeric and less than or equal to 32 - characters and greater than 0 characters in length. - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`~.field_mask.FieldMask`): - The FieldMask to use when updating the finding resource. - This field should not be specified when creating a - finding. - - When updating a finding, an empty mask is treated as - updating all mutable fields and replacing - source_properties. Individual source_properties can be - added/updated by using "source_properties." in the field - mask. - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_finding.Finding: - Security Command Center finding. - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([finding, update_mask]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.UpdateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if finding is not None: - request.finding = finding - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.update_finding, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("finding.name", request.finding.name),) - ), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def update_notification_config( - self, - request: securitycenter_service.UpdateNotificationConfigRequest = None, - *, - notification_config: gcs_notification_config.NotificationConfig = None, - update_mask: field_mask.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Args: - request (:class:`~.securitycenter_service.UpdateNotificationConfigRequest`): - The request object. Request message for updating a - notification config. - notification_config (:class:`~.gcs_notification_config.NotificationConfig`): - Required. The notification config to - update. - This corresponds to the ``notification_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`~.field_mask.FieldMask`): - The FieldMask to use when updating - the notification config. - If empty all mutable fields will be - updated. - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_notification_config.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([notification_config, update_mask]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.UpdateNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if notification_config is not None: - request.notification_config = notification_config - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.update_notification_config, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("notification_config.name", request.notification_config.name),) - ), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def update_organization_settings( - self, - request: securitycenter_service.UpdateOrganizationSettingsRequest = None, - *, - organization_settings: gcs_organization_settings.OrganizationSettings = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Updates an organization's settings. - - Args: - request (:class:`~.securitycenter_service.UpdateOrganizationSettingsRequest`): - The request object. Request message for updating an - organization's settings. - organization_settings (:class:`~.gcs_organization_settings.OrganizationSettings`): - Required. The organization settings - resource to update. - This corresponds to the ``organization_settings`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_organization_settings.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([organization_settings]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.UpdateOrganizationSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if organization_settings is not None: - request.organization_settings = organization_settings - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = gapic_v1.method_async.wrap_method( - self._client._transport.update_organization_settings, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("organization_settings.name", request.organization_settings.name),) - ), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def update_source( - self, - request: securitycenter_service.UpdateSourceRequest = None, - *, - source: gcs_source.Source = None, - update_mask: field_mask.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Updates a source. - - Args: - request (:class:`~.securitycenter_service.UpdateSourceRequest`): - The request object. Request message for updating a - source. - source (:class:`~.gcs_source.Source`): - Required. The source resource to - update. - This corresponds to the ``source`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`~.field_mask.FieldMask`): - The FieldMask to use when updating - the source resource. - If empty all mutable fields will be - updated. - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([source, update_mask]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.UpdateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if source is not None: - request.source = source - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.update_source, - default_timeout=60.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("source.name", request.source.name),) - ), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - async def update_security_marks( - self, - request: securitycenter_service.UpdateSecurityMarksRequest = None, - *, - security_marks: gcs_security_marks.SecurityMarks = None, - update_mask: field_mask.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_security_marks.SecurityMarks: - r"""Updates security marks. - - Args: - request (:class:`~.securitycenter_service.UpdateSecurityMarksRequest`): - The request object. Request message for updating a - SecurityMarks resource. - security_marks (:class:`~.gcs_security_marks.SecurityMarks`): - Required. The security marks resource - to update. - This corresponds to the ``security_marks`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`~.field_mask.FieldMask`): - The FieldMask to use when updating the security marks - resource. - - The field mask must not contain duplicate fields. If - empty or set to "marks", all marks will be replaced. - Individual marks can be updated using - "marks.". - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_security_marks.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - if request is not None and any([security_marks, update_mask]): - raise ValueError( - "If the `request` argument is set, then none of " - "the individual field arguments should be set." - ) - - request = securitycenter_service.UpdateSecurityMarksRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if security_marks is not None: - request.security_marks = security_marks - 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 = gapic_v1.method_async.wrap_method( - self._client._transport.update_security_marks, - default_timeout=480.0, - client_info=_client_info, - ) - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("security_marks.name", request.security_marks.name),) - ), - ) - - # Send the request. - response = await rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -try: - _client_info = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-securitycenter", - ).version, - ) -except pkg_resources.DistributionNotFound: - _client_info = gapic_v1.client_info.ClientInfo() - - -__all__ = ("SecurityCenterAsyncClient",) diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py deleted file mode 100644 index 80c66f10..00000000 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/client.py +++ /dev/null @@ -1,2473 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 -import os -import re -from typing import Callable, Dict, Sequence, Tuple, Type, Union -import pkg_resources - -import google.api_core.client_options as ClientOptions # type: ignore -from google.api_core import exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.auth import credentials # type: ignore -from google.auth.transport import mtls # type: ignore -from google.auth.exceptions import MutualTLSChannelError # type: ignore -from google.oauth2 import service_account # type: ignore - -from google.api_core import operation -from google.api_core import operation_async -from google.cloud.securitycenter_v1p1beta1.services.security_center import pagers -from google.cloud.securitycenter_v1p1beta1.types import finding -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import ( - notification_config as gcs_notification_config, -) -from google.cloud.securitycenter_v1p1beta1.types import organization_settings -from google.cloud.securitycenter_v1p1beta1.types import ( - organization_settings as gcs_organization_settings, -) -from google.cloud.securitycenter_v1p1beta1.types import run_asset_discovery_response -from google.cloud.securitycenter_v1p1beta1.types import security_marks -from google.cloud.securitycenter_v1p1beta1.types import ( - security_marks as gcs_security_marks, -) -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore -from google.protobuf import field_mask_pb2 as field_mask # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - -from .transports.base import SecurityCenterTransport -from .transports.grpc import SecurityCenterGrpcTransport -from .transports.grpc_asyncio import SecurityCenterGrpcAsyncIOTransport - - -class SecurityCenterClientMeta(type): - """Metaclass for the SecurityCenter 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[SecurityCenterTransport]] - _transport_registry["grpc"] = SecurityCenterGrpcTransport - _transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport - - def get_transport_class(cls, label: str = None,) -> Type[SecurityCenterTransport]: - """Return 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 SecurityCenterClient(metaclass=SecurityCenterClientMeta): - """V1p1Beta1 APIs for Security Center service.""" - - @staticmethod - def _get_default_mtls_endpoint(api_endpoint): - """Convert 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") - - DEFAULT_ENDPOINT = "securitycenter.googleapis.com" - DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore - DEFAULT_ENDPOINT - ) - - @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: - {@api.name}: 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 - - @staticmethod - def finding_path(organization: str, source: str, finding: str,) -> str: - """Return a fully-qualified finding string.""" - return "organizations/{organization}/sources/{source}/findings/{finding}".format( - organization=organization, source=source, finding=finding, - ) - - @staticmethod - def parse_finding_path(path: str) -> Dict[str, str]: - """Parse a finding path into its component segments.""" - m = re.match( - r"^organizations/(?P.+?)/sources/(?P.+?)/findings/(?P.+?)$", - path, - ) - return m.groupdict() if m else {} - - @staticmethod - def notification_config_path(organization: str, notification_config: str,) -> str: - """Return a fully-qualified notification_config string.""" - return "organizations/{organization}/notificationConfigs/{notification_config}".format( - organization=organization, notification_config=notification_config, - ) - - @staticmethod - def parse_notification_config_path(path: str) -> Dict[str, str]: - """Parse a notification_config path into its component segments.""" - m = re.match( - r"^organizations/(?P.+?)/notificationConfigs/(?P.+?)$", - path, - ) - return m.groupdict() if m else {} - - @staticmethod - def organization_settings_path(organization: str,) -> str: - """Return a fully-qualified organization_settings string.""" - return "organizations/{organization}/organizationSettings".format( - organization=organization, - ) - - @staticmethod - def parse_organization_settings_path(path: str) -> Dict[str, str]: - """Parse a organization_settings path into its component segments.""" - m = re.match( - r"^organizations/(?P.+?)/organizationSettings$", path - ) - return m.groupdict() if m else {} - - @staticmethod - def security_marks_path(organization: str, asset: str,) -> str: - """Return a fully-qualified security_marks string.""" - return "organizations/{organization}/assets/{asset}/securityMarks".format( - organization=organization, asset=asset, - ) - - @staticmethod - def parse_security_marks_path(path: str) -> Dict[str, str]: - """Parse a security_marks path into its component segments.""" - m = re.match( - r"^organizations/(?P.+?)/assets/(?P.+?)/securityMarks$", - path, - ) - return m.groupdict() if m else {} - - @staticmethod - def source_path(organization: str, source: str,) -> str: - """Return a fully-qualified source string.""" - return "organizations/{organization}/sources/{source}".format( - organization=organization, source=source, - ) - - @staticmethod - def parse_source_path(path: str) -> Dict[str, str]: - """Parse a source path into its component segments.""" - m = re.match( - r"^organizations/(?P.+?)/sources/(?P.+?)$", path - ) - return m.groupdict() if m else {} - - def __init__( - self, - *, - credentials: credentials.Credentials = None, - transport: Union[str, SecurityCenterTransport] = None, - client_options: ClientOptions = None, - ) -> None: - """Instantiate the security center 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. - transport (Union[str, ~.SecurityCenterTransport]): The - transport to use. If set to None, a transport is chosen - automatically. - client_options (ClientOptions): Custom options for the client. It - won't take effect if a ``transport`` instance is provided. - (1) The ``api_endpoint`` property can be used to override the - default endpoint provided by the client. GOOGLE_API_USE_MTLS - environment variable can also be used to override the endpoint: - "always" (always use the default mTLS endpoint), "never" (always - use the default regular endpoint, this is the default value for - the environment variable) and "auto" (auto switch to the default - mTLS endpoint if client SSL credentials is present). However, - the ``api_endpoint`` property takes precedence if provided. - (2) The ``client_cert_source`` property is used to provide client - SSL credentials for mutual TLS transport. If not provided, the - default SSL credentials will be used if present. - - Raises: - google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport - creation failed for any reason. - """ - if isinstance(client_options, dict): - client_options = ClientOptions.from_dict(client_options) - if client_options is None: - client_options = ClientOptions.ClientOptions() - - if client_options.api_endpoint is None: - use_mtls_env = os.getenv("GOOGLE_API_USE_MTLS", "never") - if use_mtls_env == "never": - client_options.api_endpoint = self.DEFAULT_ENDPOINT - elif use_mtls_env == "always": - client_options.api_endpoint = self.DEFAULT_MTLS_ENDPOINT - elif use_mtls_env == "auto": - has_client_cert_source = ( - client_options.client_cert_source is not None - or mtls.has_default_client_cert_source() - ) - client_options.api_endpoint = ( - self.DEFAULT_MTLS_ENDPOINT - if has_client_cert_source - else self.DEFAULT_ENDPOINT - ) - else: - raise MutualTLSChannelError( - "Unsupported GOOGLE_API_USE_MTLS value. Accepted values: never, auto, always" - ) - - # Save or instantiate the transport. - # Ordinarily, we provide the transport, but allowing a custom transport - # instance provides an extensibility point for unusual situations. - if isinstance(transport, SecurityCenterTransport): - # transport is a SecurityCenterTransport instance. - if credentials or client_options.credentials_file: - raise ValueError( - "When providing a transport instance, " - "provide its credentials directly." - ) - if client_options.scopes: - raise ValueError( - "When providing a transport instance, " - "provide its scopes directly." - ) - self._transport = transport - else: - Transport = type(self).get_transport_class(transport) - self._transport = Transport( - credentials=credentials, - credentials_file=client_options.credentials_file, - host=client_options.api_endpoint, - scopes=client_options.scopes, - api_mtls_endpoint=client_options.api_endpoint, - client_cert_source=client_options.client_cert_source, - quota_project_id=client_options.quota_project_id, - ) - - def create_source( - self, - request: securitycenter_service.CreateSourceRequest = None, - *, - parent: str = None, - source: gcs_source.Source = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Creates a source. - - Args: - request (:class:`~.securitycenter_service.CreateSourceRequest`): - The request object. Request message for creating a - source. - parent (:class:`str`): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - source (:class:`~.gcs_source.Source`): - Required. The Source being created, only the - display_name and description will be used. All other - fields will be ignored. - This corresponds to the ``source`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, source]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.CreateSourceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.CreateSourceRequest): - request = securitycenter_service.CreateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if source is not None: - request.source = source - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def create_finding( - self, - request: securitycenter_service.CreateFindingRequest = None, - *, - parent: str = None, - finding_id: str = None, - finding: gcs_finding.Finding = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Args: - request (:class:`~.securitycenter_service.CreateFindingRequest`): - The request object. Request message for creating a - finding. - parent (:class:`str`): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding_id (:class:`str`): - Required. Unique identifier provided - by the client within the parent scope. - It must be alphanumeric and less than or - equal to 32 characters and greater than - 0 characters in length. - This corresponds to the ``finding_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - finding (:class:`~.gcs_finding.Finding`): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output - only fields on this resource. - This corresponds to the ``finding`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_finding.Finding: - Security Command Center finding. - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, finding_id, finding]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.CreateFindingRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.CreateFindingRequest): - request = securitycenter_service.CreateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if finding_id is not None: - request.finding_id = finding_id - if finding is not None: - request.finding = finding - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.create_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def create_notification_config( - self, - request: securitycenter_service.CreateNotificationConfigRequest = None, - *, - parent: str = None, - config_id: str = None, - notification_config: gcs_notification_config.NotificationConfig = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Creates a notification config. - - Args: - request (:class:`~.securitycenter_service.CreateNotificationConfigRequest`): - The request object. Request message for creating a - notification config. - parent (:class:`str`): - Required. Resource name of the new notification config's - parent. Its format is "organizations/[organization_id]". - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - config_id (:class:`str`): - Required. - Unique identifier provided by the client - within the parent scope. It must be - between 1 and 128 characters, and - contains alphanumeric characters, - underscores or hyphens only. - This corresponds to the ``config_id`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - notification_config (:class:`~.gcs_notification_config.NotificationConfig`): - Required. The notification config - being created. The name and the service - account will be ignored as they are both - output only fields on this resource. - This corresponds to the ``notification_config`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_notification_config.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, config_id, notification_config]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.CreateNotificationConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance( - request, securitycenter_service.CreateNotificationConfigRequest - ): - request = securitycenter_service.CreateNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if config_id is not None: - request.config_id = config_id - if notification_config is not None: - request.notification_config = notification_config - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.create_notification_config - ] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def delete_notification_config( - self, - request: securitycenter_service.DeleteNotificationConfigRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> None: - r"""Deletes a notification config. - - Args: - request (:class:`~.securitycenter_service.DeleteNotificationConfigRequest`): - The request object. Request message for deleting a - notification config. - name (:class:`str`): - Required. Name of the notification config to delete. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_id]". - This corresponds to the ``name`` 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, str]]): Strings which should be - sent along with the request as metadata. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.DeleteNotificationConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance( - request, securitycenter_service.DeleteNotificationConfigRequest - ): - request = securitycenter_service.DeleteNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.delete_notification_config - ] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - rpc( - request, retry=retry, timeout=timeout, metadata=metadata, - ) - - def get_iam_policy( - self, - request: iam_policy.GetIamPolicyRequest = None, - *, - resource: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: - r"""Gets the access control policy on the specified - Source. - - Args: - request (:class:`~.iam_policy.GetIamPolicyRequest`): - The request object. Request message for `GetIamPolicy` - method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being requested. See the - operation documentation for the - appropriate value for this field. - This corresponds to the ``resource`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - 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." - ) - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.GetIamPolicyRequest(**request) - - elif not request: - request = iam_policy.GetIamPolicyRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_notification_config( - self, - request: securitycenter_service.GetNotificationConfigRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> notification_config.NotificationConfig: - r"""Gets a notification config. - - Args: - request (:class:`~.securitycenter_service.GetNotificationConfigRequest`): - The request object. Request message for getting a - notification config. - name (:class:`str`): - Required. Name of the notification config to get. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_id]". - This corresponds to the ``name`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.notification_config.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.GetNotificationConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.GetNotificationConfigRequest): - request = securitycenter_service.GetNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_notification_config] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_organization_settings( - self, - request: securitycenter_service.GetOrganizationSettingsRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> organization_settings.OrganizationSettings: - r"""Gets the settings for an organization. - - Args: - request (:class:`~.securitycenter_service.GetOrganizationSettingsRequest`): - The request object. Request message for getting - organization settings. - name (:class:`str`): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - This corresponds to the ``name`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.organization_settings.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.GetOrganizationSettingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance( - request, securitycenter_service.GetOrganizationSettingsRequest - ): - request = securitycenter_service.GetOrganizationSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.get_organization_settings - ] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def get_source( - self, - request: securitycenter_service.GetSourceRequest = None, - *, - name: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> source.Source: - r"""Gets a source. - - Args: - request (:class:`~.securitycenter_service.GetSourceRequest`): - The request object. Request message for getting a - source. - name (:class:`str`): - Required. Relative resource name of the source. Its - format is - "organizations/[organization_id]/source/[source_id]". - This corresponds to the ``name`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.GetSourceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.GetSourceRequest): - request = securitycenter_service.GetSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.get_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def group_assets( - self, - request: securitycenter_service.GroupAssetsRequest = None, - *, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupAssetsPager: - r"""Filters an organization's assets and groups them by - their specified properties. - - Args: - request (:class:`~.securitycenter_service.GroupAssetsRequest`): - The request object. Request message for grouping by - assets. - - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.GroupAssetsPager: - Response message for grouping by - assets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.GroupAssetsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.GroupAssetsRequest): - request = securitycenter_service.GroupAssetsRequest(request) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.group_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.GroupAssetsPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - def group_findings( - self, - request: securitycenter_service.GroupFindingsRequest = None, - *, - parent: str = None, - group_by: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.GroupFindingsPager: - r"""Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: - /v1p1beta1/organizations/{organization_id}/sources/-/findings - - Args: - request (:class:`~.securitycenter_service.GroupFindingsRequest`): - The request object. Request message for grouping by - findings. - parent (:class:`str`): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]". - To groupBy across all sources provide a source_id of - ``-``. For example: - organizations/{organization_id}/sources/- - This corresponds to the ``parent`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - group_by (:class:`str`): - Required. Expression that defines what assets fields to - use for grouping (including ``state_change``). The - string value should follow SQL syntax: comma separated - list of fields. For example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - - The following fields are supported when compare_duration - is set: - - - state_change - This corresponds to the ``group_by`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.GroupFindingsPager: - Response message for group by - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent, group_by]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.GroupFindingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.GroupFindingsRequest): - request = securitycenter_service.GroupFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - if group_by is not None: - request.group_by = group_by - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.group_findings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.GroupFindingsPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - def list_assets( - self, - request: securitycenter_service.ListAssetsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListAssetsPager: - r"""Lists an organization's assets. - - Args: - request (:class:`~.securitycenter_service.ListAssetsRequest`): - The request object. Request message for listing assets. - parent (:class:`str`): - Required. Name of the organization assets should belong - to. Its format is "organizations/[organization_id]". - This corresponds to the ``parent`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.ListAssetsPager: - Response message for listing assets. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.ListAssetsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.ListAssetsRequest): - request = securitycenter_service.ListAssetsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_assets] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListAssetsPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - def list_findings( - self, - request: securitycenter_service.ListFindingsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListFindingsPager: - r"""Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1p1beta1/organizations/{organization_id}/sources/-/findings - - Args: - request (:class:`~.securitycenter_service.ListFindingsRequest`): - The request object. Request message for listing - findings. - parent (:class:`str`): - Required. Name of the source the findings belong to. Its - format is - "organizations/[organization_id]/sources/[source_id]". - To list across all sources provide a source_id of ``-``. - For example: organizations/{organization_id}/sources/- - This corresponds to the ``parent`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.ListFindingsPager: - Response message for listing - findings. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.ListFindingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.ListFindingsRequest): - request = securitycenter_service.ListFindingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_findings] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListFindingsPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - def list_notification_configs( - self, - request: securitycenter_service.ListNotificationConfigsRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListNotificationConfigsPager: - r"""Lists notification configs. - - Args: - request (:class:`~.securitycenter_service.ListNotificationConfigsRequest`): - The request object. Request message for listing - notification configs. - parent (:class:`str`): - Required. Name of the organization to list notification - configs. Its format is - "organizations/[organization_id]". - This corresponds to the ``parent`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.ListNotificationConfigsPager: - Response message for listing - notification configs. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.ListNotificationConfigsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance( - request, securitycenter_service.ListNotificationConfigsRequest - ): - request = securitycenter_service.ListNotificationConfigsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.list_notification_configs - ] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListNotificationConfigsPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - def list_sources( - self, - request: securitycenter_service.ListSourcesRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> pagers.ListSourcesPager: - r"""Lists all sources belonging to an organization. - - Args: - request (:class:`~.securitycenter_service.ListSourcesRequest`): - The request object. Request message for listing sources. - parent (:class:`str`): - Required. Resource name of the parent of sources to - list. Its format should be - "organizations/[organization_id]". - This corresponds to the ``parent`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.pagers.ListSourcesPager: - Response message for listing sources. - Iterating over this object will yield - results and resolve additional pages - automatically. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.ListSourcesRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.ListSourcesRequest): - request = securitycenter_service.ListSourcesRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.list_sources] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # This method is paged; wrap the response in a pager, which provides - # an `__iter__` convenience method. - response = pagers.ListSourcesPager( - method=rpc, request=request, response=response, metadata=metadata, - ) - - # Done; return the response. - return response - - def run_asset_discovery( - self, - request: securitycenter_service.RunAssetDiscoveryRequest = None, - *, - parent: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> operation.Operation: - r"""Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Args: - request (:class:`~.securitycenter_service.RunAssetDiscoveryRequest`): - The request object. Request message for running asset - discovery for an organization. - parent (:class:`str`): - Required. Name of the organization to run asset - discovery for. Its format is - "organizations/[organization_id]". - This corresponds to the ``parent`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.operation.Operation: - An object representing a long-running operation. - - The result type for the operation will be - :class:``~.run_asset_discovery_response.RunAssetDiscoveryResponse``: - Response of asset discovery run - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([parent]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.RunAssetDiscoveryRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.RunAssetDiscoveryRequest): - request = securitycenter_service.RunAssetDiscoveryRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if parent is not None: - request.parent = parent - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.run_asset_discovery] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Wrap the response in an operation future. - response = operation.from_gapic( - response, - self._transport.operations_client, - run_asset_discovery_response.RunAssetDiscoveryResponse, - metadata_type=empty.Empty, - ) - - # Done; return the response. - return response - - def set_finding_state( - self, - request: securitycenter_service.SetFindingStateRequest = None, - *, - name: str = None, - state: finding.Finding.State = None, - start_time: timestamp.Timestamp = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> finding.Finding: - r"""Updates the state of a finding. - - Args: - request (:class:`~.securitycenter_service.SetFindingStateRequest`): - The request object. Request message for updating a - finding's state. - name (:class:`str`): - Required. The relative resource name of the finding. - See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - This corresponds to the ``name`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - state (:class:`~.finding.Finding.State`): - Required. The desired State of the - finding. - This corresponds to the ``state`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - start_time (:class:`~.timestamp.Timestamp`): - Required. The time at which the - updated state takes effect. - This corresponds to the ``start_time`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.finding.Finding: - Security Command Center finding. - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([name, state, start_time]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.SetFindingStateRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.SetFindingStateRequest): - request = securitycenter_service.SetFindingStateRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if name is not None: - request.name = name - if state is not None: - request.state = state - if start_time is not None: - request.start_time = start_time - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_finding_state] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def set_iam_policy( - self, - request: iam_policy.SetIamPolicyRequest = None, - *, - resource: str = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> policy.Policy: - r"""Sets the access control policy on the specified - Source. - - Args: - request (:class:`~.iam_policy.SetIamPolicyRequest`): - The request object. Request message for `SetIamPolicy` - method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy is being specified. See the - operation documentation for the - appropriate value for this field. - This corresponds to the ``resource`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.policy.Policy: - Defines an Identity and Access Management (IAM) policy. - It is used to specify access control policies for Cloud - Platform resources. - - A ``Policy`` is a collection of ``bindings``. A - ``binding`` binds one or more ``members`` to a single - ``role``. Members can be user accounts, service - accounts, Google groups, and domains (such as G Suite). - A ``role`` is a named list of permissions (defined by - IAM or configured by users). A ``binding`` can - optionally specify a ``condition``, which is a logic - expression that further constrains the role binding - based on attributes about the request and/or target - resource. - - **JSON Example** - - :: - - { - "bindings": [ - { - "role": "roles/resourcemanager.organizationAdmin", - "members": [ - "user:mike@example.com", - "group:admins@example.com", - "domain:google.com", - "serviceAccount:my-project-id@appspot.gserviceaccount.com" - ] - }, - { - "role": "roles/resourcemanager.organizationViewer", - "members": ["user:eve@example.com"], - "condition": { - "title": "expirable access", - "description": "Does not grant access after Sep 2020", - "expression": "request.time < - timestamp('2020-10-01T00:00:00.000Z')", - } - } - ] - } - - **YAML Example** - - :: - - bindings: - - members: - - user:mike@example.com - - group:admins@example.com - - domain:google.com - - serviceAccount:my-project-id@appspot.gserviceaccount.com - role: roles/resourcemanager.organizationAdmin - - members: - - user:eve@example.com - role: roles/resourcemanager.organizationViewer - condition: - title: expirable access - description: Does not grant access after Sep 2020 - expression: request.time < timestamp('2020-10-01T00:00:00.000Z') - - For a description of IAM and its features, see the `IAM - developer's - guide `__. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource]) - 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." - ) - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.SetIamPolicyRequest(**request) - - elif not request: - request = iam_policy.SetIamPolicyRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def test_iam_permissions( - self, - request: iam_policy.TestIamPermissionsRequest = None, - *, - resource: str = None, - permissions: Sequence[str] = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> iam_policy.TestIamPermissionsResponse: - r"""Returns the permissions that a caller has on the - specified source. - - Args: - request (:class:`~.iam_policy.TestIamPermissionsRequest`): - The request object. Request message for - `TestIamPermissions` method. - resource (:class:`str`): - REQUIRED: The resource for which the - policy detail is being requested. See - the operation documentation for the - appropriate value for this field. - This corresponds to the ``resource`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - permissions (:class:`Sequence[str]`): - The set of permissions to check for the ``resource``. - Permissions with wildcards (such as '*' or 'storage.*') - are not allowed. For more information see `IAM - Overview `__. - This corresponds to the ``permissions`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.iam_policy.TestIamPermissionsResponse: - Response message for ``TestIamPermissions`` method. - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([resource, permissions]) - 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." - ) - - # The request isn't a proto-plus wrapped type, - # so it must be constructed via keyword expansion. - if isinstance(request, dict): - request = iam_policy.TestIamPermissionsRequest(**request) - - elif not request: - request = iam_policy.TestIamPermissionsRequest() - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if resource is not None: - request.resource = resource - - if permissions: - request.permissions.extend(permissions) - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def update_finding( - self, - request: securitycenter_service.UpdateFindingRequest = None, - *, - finding: gcs_finding.Finding = None, - update_mask: field_mask.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_finding.Finding: - r"""Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Args: - request (:class:`~.securitycenter_service.UpdateFindingRequest`): - The request object. Request message for updating or - creating a finding. - finding (:class:`~.gcs_finding.Finding`): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the - name must be alphanumeric and less than or equal to 32 - characters and greater than 0 characters in length. - This corresponds to the ``finding`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`~.field_mask.FieldMask`): - The FieldMask to use when updating the finding resource. - This field should not be specified when creating a - finding. - - When updating a finding, an empty mask is treated as - updating all mutable fields and replacing - source_properties. Individual source_properties can be - added/updated by using "source_properties." in the field - mask. - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_finding.Finding: - Security Command Center finding. - A finding is a record of assessment data - (security, risk, health or privacy) - ingested into Security Command Center - for presentation, notification, - analysis, policy testing, and - enforcement. For example, an XSS - vulnerability in an App Engine - application is a finding. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([finding, update_mask]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.UpdateFindingRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.UpdateFindingRequest): - request = securitycenter_service.UpdateFindingRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if finding is not None: - request.finding = finding - 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_finding] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("finding.name", request.finding.name),) - ), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def update_notification_config( - self, - request: securitycenter_service.UpdateNotificationConfigRequest = None, - *, - notification_config: gcs_notification_config.NotificationConfig = None, - update_mask: field_mask.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_notification_config.NotificationConfig: - r"""Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Args: - request (:class:`~.securitycenter_service.UpdateNotificationConfigRequest`): - The request object. Request message for updating a - notification config. - notification_config (:class:`~.gcs_notification_config.NotificationConfig`): - Required. The notification config to - update. - This corresponds to the ``notification_config`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`~.field_mask.FieldMask`): - The FieldMask to use when updating - the notification config. - If empty all mutable fields will be - updated. - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_notification_config.NotificationConfig: - Security Command Center notification - configs. - A notification config is a Security - Command Center resource that contains - the configuration to send notifications - for create/update events of findings, - assets and etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([notification_config, update_mask]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.UpdateNotificationConfigRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance( - request, securitycenter_service.UpdateNotificationConfigRequest - ): - request = securitycenter_service.UpdateNotificationConfigRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if notification_config is not None: - request.notification_config = notification_config - 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_notification_config - ] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("notification_config.name", request.notification_config.name),) - ), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def update_organization_settings( - self, - request: securitycenter_service.UpdateOrganizationSettingsRequest = None, - *, - organization_settings: gcs_organization_settings.OrganizationSettings = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_organization_settings.OrganizationSettings: - r"""Updates an organization's settings. - - Args: - request (:class:`~.securitycenter_service.UpdateOrganizationSettingsRequest`): - The request object. Request message for updating an - organization's settings. - organization_settings (:class:`~.gcs_organization_settings.OrganizationSettings`): - Required. The organization settings - resource to update. - This corresponds to the ``organization_settings`` 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_organization_settings.OrganizationSettings: - User specified settings that are - attached to the Security Command Center - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([organization_settings]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.UpdateOrganizationSettingsRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance( - request, securitycenter_service.UpdateOrganizationSettingsRequest - ): - request = securitycenter_service.UpdateOrganizationSettingsRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if organization_settings is not None: - request.organization_settings = organization_settings - - # Wrap the RPC method; this adds retry and timeout information, - # and friendly error handling. - rpc = self._transport._wrapped_methods[ - self._transport.update_organization_settings - ] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("organization_settings.name", request.organization_settings.name),) - ), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def update_source( - self, - request: securitycenter_service.UpdateSourceRequest = None, - *, - source: gcs_source.Source = None, - update_mask: field_mask.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_source.Source: - r"""Updates a source. - - Args: - request (:class:`~.securitycenter_service.UpdateSourceRequest`): - The request object. Request message for updating a - source. - source (:class:`~.gcs_source.Source`): - Required. The source resource to - update. - This corresponds to the ``source`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`~.field_mask.FieldMask`): - The FieldMask to use when updating - the source resource. - If empty all mutable fields will be - updated. - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_source.Source: - Security Command Center finding - source. A finding source is an entity or - a mechanism that can produce a finding. - A source is like a container of findings - that come from the same scanner, logger, - monitor, etc. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([source, update_mask]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.UpdateSourceRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.UpdateSourceRequest): - request = securitycenter_service.UpdateSourceRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if source is not None: - request.source = source - 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_source] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("source.name", request.source.name),) - ), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - def update_security_marks( - self, - request: securitycenter_service.UpdateSecurityMarksRequest = None, - *, - security_marks: gcs_security_marks.SecurityMarks = None, - update_mask: field_mask.FieldMask = None, - retry: retries.Retry = gapic_v1.method.DEFAULT, - timeout: float = None, - metadata: Sequence[Tuple[str, str]] = (), - ) -> gcs_security_marks.SecurityMarks: - r"""Updates security marks. - - Args: - request (:class:`~.securitycenter_service.UpdateSecurityMarksRequest`): - The request object. Request message for updating a - SecurityMarks resource. - security_marks (:class:`~.gcs_security_marks.SecurityMarks`): - Required. The security marks resource - to update. - This corresponds to the ``security_marks`` field - on the ``request`` instance; if ``request`` is provided, this - should not be set. - update_mask (:class:`~.field_mask.FieldMask`): - The FieldMask to use when updating the security marks - resource. - - The field mask must not contain duplicate fields. If - empty or set to "marks", all marks will be replaced. - Individual marks can be updated using - "marks.". - 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, str]]): Strings which should be - sent along with the request as metadata. - - Returns: - ~.gcs_security_marks.SecurityMarks: - User specified security marks that - are attached to the parent Security - Command Center resource. Security marks - are scoped within a Security Command - Center organization -- they can be - modified and viewed by all users who - have proper permissions on the - organization. - - """ - # Create or coerce a protobuf request object. - # Sanity check: If we got a request object, we should *not* have - # gotten any keyword arguments that map to the request. - has_flattened_params = any([security_marks, update_mask]) - 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." - ) - - # Minor optimization to avoid making a copy if the user passes - # in a securitycenter_service.UpdateSecurityMarksRequest. - # There's no risk of modifying the input as we've already verified - # there are no flattened fields. - if not isinstance(request, securitycenter_service.UpdateSecurityMarksRequest): - request = securitycenter_service.UpdateSecurityMarksRequest(request) - - # If we have keyword arguments corresponding to fields on the - # request, apply these. - - if security_marks is not None: - request.security_marks = security_marks - 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_security_marks] - - # Certain fields should be provided within the metadata header; - # add these here. - metadata = tuple(metadata) + ( - gapic_v1.routing_header.to_grpc_metadata( - (("security_marks.name", request.security_marks.name),) - ), - ) - - # Send the request. - response = rpc(request, retry=retry, timeout=timeout, metadata=metadata,) - - # Done; return the response. - return response - - -try: - _client_info = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-securitycenter", - ).version, - ) -except pkg_resources.DistributionNotFound: - _client_info = gapic_v1.client_info.ClientInfo() - - -__all__ = ("SecurityCenterClient",) diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py deleted file mode 100644 index 561db76f..00000000 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/pagers.py +++ /dev/null @@ -1,804 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 typing import Any, AsyncIterable, Awaitable, Callable, Iterable, Sequence, Tuple - -from google.cloud.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source - - -class GroupAssetsPager: - """A pager for iterating through ``group_assets`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.GroupAssetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``GroupAssets`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.GroupAssetsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., securitycenter_service.GroupAssetsResponse], - request: securitycenter_service.GroupAssetsRequest, - response: securitycenter_service.GroupAssetsResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.GroupAssetsRequest`): - The initial request object. - response (:class:`~.securitycenter_service.GroupAssetsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.GroupAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.GroupAssetsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[securitycenter_service.GroupResult]: - for page in self.pages: - yield from page.group_by_results - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class GroupAssetsAsyncPager: - """A pager for iterating through ``group_assets`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.GroupAssetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``GroupAssets`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.GroupAssetsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., Awaitable[securitycenter_service.GroupAssetsResponse]], - request: securitycenter_service.GroupAssetsRequest, - response: securitycenter_service.GroupAssetsResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.GroupAssetsRequest`): - The initial request object. - response (:class:`~.securitycenter_service.GroupAssetsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.GroupAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.GroupAssetsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[securitycenter_service.GroupResult]: - async def async_generator(): - async for page in self.pages: - for response in page.group_by_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class GroupFindingsPager: - """A pager for iterating through ``group_findings`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.GroupFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``GroupFindings`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.GroupFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., securitycenter_service.GroupFindingsResponse], - request: securitycenter_service.GroupFindingsRequest, - response: securitycenter_service.GroupFindingsResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.GroupFindingsRequest`): - The initial request object. - response (:class:`~.securitycenter_service.GroupFindingsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.GroupFindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.GroupFindingsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[securitycenter_service.GroupResult]: - for page in self.pages: - yield from page.group_by_results - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class GroupFindingsAsyncPager: - """A pager for iterating through ``group_findings`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.GroupFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``group_by_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``GroupFindings`` requests and continue to iterate - through the ``group_by_results`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.GroupFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., Awaitable[securitycenter_service.GroupFindingsResponse]], - request: securitycenter_service.GroupFindingsRequest, - response: securitycenter_service.GroupFindingsResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.GroupFindingsRequest`): - The initial request object. - response (:class:`~.securitycenter_service.GroupFindingsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.GroupFindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages( - self, - ) -> AsyncIterable[securitycenter_service.GroupFindingsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[securitycenter_service.GroupResult]: - async def async_generator(): - async for page in self.pages: - for response in page.group_by_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListAssetsPager: - """A pager for iterating through ``list_assets`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.ListAssetsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``list_assets_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListAssets`` requests and continue to iterate - through the ``list_assets_results`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.ListAssetsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., securitycenter_service.ListAssetsResponse], - request: securitycenter_service.ListAssetsRequest, - response: securitycenter_service.ListAssetsResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.ListAssetsRequest`): - The initial request object. - response (:class:`~.securitycenter_service.ListAssetsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.ListAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.ListAssetsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__( - self, - ) -> Iterable[securitycenter_service.ListAssetsResponse.ListAssetsResult]: - for page in self.pages: - yield from page.list_assets_results - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListAssetsAsyncPager: - """A pager for iterating through ``list_assets`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.ListAssetsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``list_assets_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListAssets`` requests and continue to iterate - through the ``list_assets_results`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.ListAssetsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., Awaitable[securitycenter_service.ListAssetsResponse]], - request: securitycenter_service.ListAssetsRequest, - response: securitycenter_service.ListAssetsResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.ListAssetsRequest`): - The initial request object. - response (:class:`~.securitycenter_service.ListAssetsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.ListAssetsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.ListAssetsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__( - self, - ) -> AsyncIterable[securitycenter_service.ListAssetsResponse.ListAssetsResult]: - async def async_generator(): - async for page in self.pages: - for response in page.list_assets_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListFindingsPager: - """A pager for iterating through ``list_findings`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.ListFindingsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``list_findings_results`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``list_findings_results`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.ListFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., securitycenter_service.ListFindingsResponse], - request: securitycenter_service.ListFindingsRequest, - response: securitycenter_service.ListFindingsResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.ListFindingsRequest`): - The initial request object. - response (:class:`~.securitycenter_service.ListFindingsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.ListFindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.ListFindingsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__( - self, - ) -> Iterable[securitycenter_service.ListFindingsResponse.ListFindingsResult]: - for page in self.pages: - yield from page.list_findings_results - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListFindingsAsyncPager: - """A pager for iterating through ``list_findings`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.ListFindingsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``list_findings_results`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListFindings`` requests and continue to iterate - through the ``list_findings_results`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.ListFindingsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., Awaitable[securitycenter_service.ListFindingsResponse]], - request: securitycenter_service.ListFindingsRequest, - response: securitycenter_service.ListFindingsResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.ListFindingsRequest`): - The initial request object. - response (:class:`~.securitycenter_service.ListFindingsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.ListFindingsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.ListFindingsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__( - self, - ) -> AsyncIterable[securitycenter_service.ListFindingsResponse.ListFindingsResult]: - async def async_generator(): - async for page in self.pages: - for response in page.list_findings_results: - yield response - - return async_generator() - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListNotificationConfigsPager: - """A pager for iterating through ``list_notification_configs`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.ListNotificationConfigsResponse` object, and - provides an ``__iter__`` method to iterate through its - ``notification_configs`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListNotificationConfigs`` requests and continue to iterate - through the ``notification_configs`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.ListNotificationConfigsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., securitycenter_service.ListNotificationConfigsResponse], - request: securitycenter_service.ListNotificationConfigsRequest, - response: securitycenter_service.ListNotificationConfigsResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.ListNotificationConfigsRequest`): - The initial request object. - response (:class:`~.securitycenter_service.ListNotificationConfigsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.ListNotificationConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.ListNotificationConfigsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[notification_config.NotificationConfig]: - for page in self.pages: - yield from page.notification_configs - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListNotificationConfigsAsyncPager: - """A pager for iterating through ``list_notification_configs`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.ListNotificationConfigsResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``notification_configs`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListNotificationConfigs`` requests and continue to iterate - through the ``notification_configs`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.ListNotificationConfigsResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[ - ..., Awaitable[securitycenter_service.ListNotificationConfigsResponse] - ], - request: securitycenter_service.ListNotificationConfigsRequest, - response: securitycenter_service.ListNotificationConfigsResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.ListNotificationConfigsRequest`): - The initial request object. - response (:class:`~.securitycenter_service.ListNotificationConfigsResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.ListNotificationConfigsRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages( - self, - ) -> AsyncIterable[securitycenter_service.ListNotificationConfigsResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[notification_config.NotificationConfig]: - async def async_generator(): - async for page in self.pages: - for response in page.notification_configs: - yield response - - return async_generator() - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListSourcesPager: - """A pager for iterating through ``list_sources`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.ListSourcesResponse` object, and - provides an ``__iter__`` method to iterate through its - ``sources`` field. - - If there are more pages, the ``__iter__`` method will make additional - ``ListSources`` requests and continue to iterate - through the ``sources`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.ListSourcesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., securitycenter_service.ListSourcesResponse], - request: securitycenter_service.ListSourcesRequest, - response: securitycenter_service.ListSourcesResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.ListSourcesRequest`): - The initial request object. - response (:class:`~.securitycenter_service.ListSourcesResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.ListSourcesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - def pages(self) -> Iterable[securitycenter_service.ListSourcesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = self._method(self._request, metadata=self._metadata) - yield self._response - - def __iter__(self) -> Iterable[source.Source]: - for page in self.pages: - yield from page.sources - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) - - -class ListSourcesAsyncPager: - """A pager for iterating through ``list_sources`` requests. - - This class thinly wraps an initial - :class:`~.securitycenter_service.ListSourcesResponse` object, and - provides an ``__aiter__`` method to iterate through its - ``sources`` field. - - If there are more pages, the ``__aiter__`` method will make additional - ``ListSources`` requests and continue to iterate - through the ``sources`` field on the - corresponding responses. - - All the usual :class:`~.securitycenter_service.ListSourcesResponse` - attributes are available on the pager. If multiple requests are made, only - the most recent response is retained, and thus used for attribute lookup. - """ - - def __init__( - self, - method: Callable[..., Awaitable[securitycenter_service.ListSourcesResponse]], - request: securitycenter_service.ListSourcesRequest, - response: securitycenter_service.ListSourcesResponse, - *, - metadata: Sequence[Tuple[str, str]] = () - ): - """Instantiate the pager. - - Args: - method (Callable): The method that was originally called, and - which instantiated this pager. - request (:class:`~.securitycenter_service.ListSourcesRequest`): - The initial request object. - response (:class:`~.securitycenter_service.ListSourcesResponse`): - The initial response object. - metadata (Sequence[Tuple[str, str]]): Strings which should be - sent along with the request as metadata. - """ - self._method = method - self._request = securitycenter_service.ListSourcesRequest(request) - self._response = response - self._metadata = metadata - - def __getattr__(self, name: str) -> Any: - return getattr(self._response, name) - - @property - async def pages(self) -> AsyncIterable[securitycenter_service.ListSourcesResponse]: - yield self._response - while self._response.next_page_token: - self._request.page_token = self._response.next_page_token - self._response = await self._method(self._request, metadata=self._metadata) - yield self._response - - def __aiter__(self) -> AsyncIterable[source.Source]: - async def async_generator(): - async for page in self.pages: - for response in page.sources: - yield response - - return async_generator() - - def __repr__(self) -> str: - return "{0}<{1!r}>".format(self.__class__.__name__, self._response) diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py deleted file mode 100644 index 20423f2a..00000000 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/__init__.py +++ /dev/null @@ -1,36 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 typing import Dict, Type - -from .base import SecurityCenterTransport -from .grpc import SecurityCenterGrpcTransport -from .grpc_asyncio import SecurityCenterGrpcAsyncIOTransport - - -# Compile a registry of transports. -_transport_registry = OrderedDict() # type: Dict[str, Type[SecurityCenterTransport]] -_transport_registry["grpc"] = SecurityCenterGrpcTransport -_transport_registry["grpc_asyncio"] = SecurityCenterGrpcAsyncIOTransport - - -__all__ = ( - "SecurityCenterTransport", - "SecurityCenterGrpcTransport", - "SecurityCenterGrpcAsyncIOTransport", -) diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py deleted file mode 100644 index d506c7bc..00000000 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/base.py +++ /dev/null @@ -1,568 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 -import typing -import pkg_resources - -from google import auth -from google.api_core import exceptions # type: ignore -from google.api_core import gapic_v1 # type: ignore -from google.api_core import retry as retries # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore - -from google.cloud.securitycenter_v1p1beta1.types import finding -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import ( - notification_config as gcs_notification_config, -) -from google.cloud.securitycenter_v1p1beta1.types import organization_settings -from google.cloud.securitycenter_v1p1beta1.types import ( - organization_settings as gcs_organization_settings, -) -from google.cloud.securitycenter_v1p1beta1.types import ( - security_marks as gcs_security_marks, -) -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - - -try: - _client_info = gapic_v1.client_info.ClientInfo( - gapic_version=pkg_resources.get_distribution( - "google-cloud-securitycenter", - ).version, - ) -except pkg_resources.DistributionNotFound: - _client_info = gapic_v1.client_info.ClientInfo() - - -class SecurityCenterTransport(abc.ABC): - """Abstract transport class for SecurityCenter.""" - - AUTH_SCOPES = ("https://www.googleapis.com/auth/cloud-platform",) - - def __init__( - self, - *, - host: str = "securitycenter.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: typing.Optional[str] = None, - scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES, - quota_project_id: typing.Optional[str] = None, - **kwargs, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): The hostname to connect to. - 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]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scope (Optional[Sequence[str]]): A list of scopes. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - """ - # Save the hostname. Default to port 443 (HTTPS) if none is specified. - if ":" not in host: - host += ":443" - self._host = host - - # If no credentials are provided, then determine the appropriate - # defaults. - if credentials and credentials_file: - raise exceptions.DuplicateCredentialArgs( - "'credentials_file' and 'credentials' are mutually exclusive" - ) - - if credentials_file is not None: - credentials, _ = auth.load_credentials_from_file( - credentials_file, scopes=scopes, quota_project_id=quota_project_id - ) - - elif credentials is None: - credentials, _ = auth.default( - scopes=scopes, quota_project_id=quota_project_id - ) - - # Save the credentials. - self._credentials = credentials - - # Lifted into its own function so it can be stubbed out during tests. - self._prep_wrapped_messages() - - def _prep_wrapped_messages(self): - # Precompute the wrapped methods. - self._wrapped_methods = { - self.create_source: gapic_v1.method.wrap_method( - self.create_source, default_timeout=60.0, client_info=_client_info, - ), - self.create_finding: gapic_v1.method.wrap_method( - self.create_finding, default_timeout=60.0, client_info=_client_info, - ), - self.create_notification_config: gapic_v1.method.wrap_method( - self.create_notification_config, - default_timeout=60.0, - client_info=_client_info, - ), - self.delete_notification_config: gapic_v1.method.wrap_method( - self.delete_notification_config, - default_timeout=60.0, - client_info=_client_info, - ), - self.get_iam_policy: gapic_v1.method.wrap_method( - self.get_iam_policy, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ), - self.get_notification_config: gapic_v1.method.wrap_method( - self.get_notification_config, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ), - self.get_organization_settings: gapic_v1.method.wrap_method( - self.get_organization_settings, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ), - self.get_source: gapic_v1.method.wrap_method( - self.get_source, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ), - self.group_assets: gapic_v1.method.wrap_method( - self.group_assets, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ), - self.group_findings: gapic_v1.method.wrap_method( - self.group_findings, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ), - self.list_assets: gapic_v1.method.wrap_method( - self.list_assets, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ), - self.list_findings: gapic_v1.method.wrap_method( - self.list_findings, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=480.0, - client_info=_client_info, - ), - self.list_notification_configs: gapic_v1.method.wrap_method( - self.list_notification_configs, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ), - self.list_sources: gapic_v1.method.wrap_method( - self.list_sources, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ), - self.run_asset_discovery: gapic_v1.method.wrap_method( - self.run_asset_discovery, - default_timeout=60.0, - client_info=_client_info, - ), - self.set_finding_state: gapic_v1.method.wrap_method( - self.set_finding_state, default_timeout=60.0, client_info=_client_info, - ), - self.set_iam_policy: gapic_v1.method.wrap_method( - self.set_iam_policy, default_timeout=60.0, client_info=_client_info, - ), - self.test_iam_permissions: gapic_v1.method.wrap_method( - self.test_iam_permissions, - default_retry=retries.Retry( - initial=0.1, - maximum=60.0, - multiplier=1.3, - predicate=retries.if_exception_type( - exceptions.ServiceUnavailable, exceptions.DeadlineExceeded, - ), - ), - default_timeout=60.0, - client_info=_client_info, - ), - self.update_finding: gapic_v1.method.wrap_method( - self.update_finding, default_timeout=60.0, client_info=_client_info, - ), - self.update_notification_config: gapic_v1.method.wrap_method( - self.update_notification_config, - default_timeout=60.0, - client_info=_client_info, - ), - self.update_organization_settings: gapic_v1.method.wrap_method( - self.update_organization_settings, - default_timeout=60.0, - client_info=_client_info, - ), - self.update_source: gapic_v1.method.wrap_method( - self.update_source, default_timeout=60.0, client_info=_client_info, - ), - self.update_security_marks: gapic_v1.method.wrap_method( - self.update_security_marks, - default_timeout=480.0, - client_info=_client_info, - ), - } - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Return the client designed to process long-running operations.""" - raise NotImplementedError() - - @property - def create_source( - self, - ) -> typing.Callable[ - [securitycenter_service.CreateSourceRequest], - typing.Union[gcs_source.Source, typing.Awaitable[gcs_source.Source]], - ]: - raise NotImplementedError() - - @property - def create_finding( - self, - ) -> typing.Callable[ - [securitycenter_service.CreateFindingRequest], - typing.Union[gcs_finding.Finding, typing.Awaitable[gcs_finding.Finding]], - ]: - raise NotImplementedError() - - @property - def create_notification_config( - self, - ) -> typing.Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - typing.Union[ - gcs_notification_config.NotificationConfig, - typing.Awaitable[gcs_notification_config.NotificationConfig], - ], - ]: - raise NotImplementedError() - - @property - def delete_notification_config( - self, - ) -> typing.Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], - typing.Union[empty.Empty, typing.Awaitable[empty.Empty]], - ]: - raise NotImplementedError() - - @property - def get_iam_policy( - self, - ) -> typing.Callable[ - [iam_policy.GetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], - ]: - raise NotImplementedError() - - @property - def get_notification_config( - self, - ) -> typing.Callable[ - [securitycenter_service.GetNotificationConfigRequest], - typing.Union[ - notification_config.NotificationConfig, - typing.Awaitable[notification_config.NotificationConfig], - ], - ]: - raise NotImplementedError() - - @property - def get_organization_settings( - self, - ) -> typing.Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - typing.Union[ - organization_settings.OrganizationSettings, - typing.Awaitable[organization_settings.OrganizationSettings], - ], - ]: - raise NotImplementedError() - - @property - def get_source( - self, - ) -> typing.Callable[ - [securitycenter_service.GetSourceRequest], - typing.Union[source.Source, typing.Awaitable[source.Source]], - ]: - raise NotImplementedError() - - @property - def group_assets( - self, - ) -> typing.Callable[ - [securitycenter_service.GroupAssetsRequest], - typing.Union[ - securitycenter_service.GroupAssetsResponse, - typing.Awaitable[securitycenter_service.GroupAssetsResponse], - ], - ]: - raise NotImplementedError() - - @property - def group_findings( - self, - ) -> typing.Callable[ - [securitycenter_service.GroupFindingsRequest], - typing.Union[ - securitycenter_service.GroupFindingsResponse, - typing.Awaitable[securitycenter_service.GroupFindingsResponse], - ], - ]: - raise NotImplementedError() - - @property - def list_assets( - self, - ) -> typing.Callable[ - [securitycenter_service.ListAssetsRequest], - typing.Union[ - securitycenter_service.ListAssetsResponse, - typing.Awaitable[securitycenter_service.ListAssetsResponse], - ], - ]: - raise NotImplementedError() - - @property - def list_findings( - self, - ) -> typing.Callable[ - [securitycenter_service.ListFindingsRequest], - typing.Union[ - securitycenter_service.ListFindingsResponse, - typing.Awaitable[securitycenter_service.ListFindingsResponse], - ], - ]: - raise NotImplementedError() - - @property - def list_notification_configs( - self, - ) -> typing.Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - typing.Union[ - securitycenter_service.ListNotificationConfigsResponse, - typing.Awaitable[securitycenter_service.ListNotificationConfigsResponse], - ], - ]: - raise NotImplementedError() - - @property - def list_sources( - self, - ) -> typing.Callable[ - [securitycenter_service.ListSourcesRequest], - typing.Union[ - securitycenter_service.ListSourcesResponse, - typing.Awaitable[securitycenter_service.ListSourcesResponse], - ], - ]: - raise NotImplementedError() - - @property - def run_asset_discovery( - self, - ) -> typing.Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - typing.Union[operations.Operation, typing.Awaitable[operations.Operation]], - ]: - raise NotImplementedError() - - @property - def set_finding_state( - self, - ) -> typing.Callable[ - [securitycenter_service.SetFindingStateRequest], - typing.Union[finding.Finding, typing.Awaitable[finding.Finding]], - ]: - raise NotImplementedError() - - @property - def set_iam_policy( - self, - ) -> typing.Callable[ - [iam_policy.SetIamPolicyRequest], - typing.Union[policy.Policy, typing.Awaitable[policy.Policy]], - ]: - raise NotImplementedError() - - @property - def test_iam_permissions( - self, - ) -> typing.Callable[ - [iam_policy.TestIamPermissionsRequest], - typing.Union[ - iam_policy.TestIamPermissionsResponse, - typing.Awaitable[iam_policy.TestIamPermissionsResponse], - ], - ]: - raise NotImplementedError() - - @property - def update_finding( - self, - ) -> typing.Callable[ - [securitycenter_service.UpdateFindingRequest], - typing.Union[gcs_finding.Finding, typing.Awaitable[gcs_finding.Finding]], - ]: - raise NotImplementedError() - - @property - def update_notification_config( - self, - ) -> typing.Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - typing.Union[ - gcs_notification_config.NotificationConfig, - typing.Awaitable[gcs_notification_config.NotificationConfig], - ], - ]: - raise NotImplementedError() - - @property - def update_organization_settings( - self, - ) -> typing.Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - typing.Union[ - gcs_organization_settings.OrganizationSettings, - typing.Awaitable[gcs_organization_settings.OrganizationSettings], - ], - ]: - raise NotImplementedError() - - @property - def update_source( - self, - ) -> typing.Callable[ - [securitycenter_service.UpdateSourceRequest], - typing.Union[gcs_source.Source, typing.Awaitable[gcs_source.Source]], - ]: - raise NotImplementedError() - - @property - def update_security_marks( - self, - ) -> typing.Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - typing.Union[ - gcs_security_marks.SecurityMarks, - typing.Awaitable[gcs_security_marks.SecurityMarks], - ], - ]: - raise NotImplementedError() - - -__all__ = ("SecurityCenterTransport",) diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py deleted file mode 100644 index b1169fde..00000000 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc.py +++ /dev/null @@ -1,904 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 typing import Callable, Dict, Optional, Sequence, Tuple - -from google.api_core import grpc_helpers # type: ignore -from google.api_core import operations_v1 # type: ignore -from google import auth # type: ignore -from google.auth import credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - - -import grpc # type: ignore - -from google.cloud.securitycenter_v1p1beta1.types import finding -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import ( - notification_config as gcs_notification_config, -) -from google.cloud.securitycenter_v1p1beta1.types import organization_settings -from google.cloud.securitycenter_v1p1beta1.types import ( - organization_settings as gcs_organization_settings, -) -from google.cloud.securitycenter_v1p1beta1.types import ( - security_marks as gcs_security_marks, -) -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - -from .base import SecurityCenterTransport - - -class SecurityCenterGrpcTransport(SecurityCenterTransport): - """gRPC backend transport for SecurityCenter. - - V1p1Beta1 APIs for Security Center service. - - 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 = "securitycenter.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: str = None, - scopes: Sequence[str] = None, - channel: grpc.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id: Optional[str] = None - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): The hostname to connect to. - 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 ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional(Sequence[str])): A list of scopes. This argument is - ignored if ``channel`` is provided. - channel (Optional[grpc.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): 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 applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 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. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - - 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. - """ - if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. - credentials = False - - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - if credentials is None: - credentials, _ = auth.default( - scopes=self.AUTH_SCOPES, quota_project_id=quota_project_id - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - ) - - self._stubs = {} # type: Dict[str, Callable] - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - ) - - @classmethod - def create_channel( - cls, - host: str = "securitycenter.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: str = None, - scopes: Optional[Sequence[str]] = None, - quota_project_id: Optional[str] = None, - **kwargs - ) -> grpc.Channel: - """Create and return a gRPC channel object. - Args: - address (Optionsl[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]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is mutually exclusive with credentials. - scopes (Optional[Sequence[str]]): A optional 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. - """ - scopes = scopes or cls.AUTH_SCOPES - return grpc_helpers.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - **kwargs - ) - - @property - def grpc_channel(self) -> grpc.Channel: - """Create the channel designed to connect to this service. - - This property caches on the instance; repeated calls return - the same channel. - """ - # Sanity check: Only create a new channel if we do not already - # have one. - if not hasattr(self, "_grpc_channel"): - self._grpc_channel = self.create_channel( - self._host, credentials=self._credentials, - ) - - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if "operations_client" not in self.__dict__: - self.__dict__["operations_client"] = operations_v1.OperationsClient( - self.grpc_channel - ) - - # Return the client from cache. - return self.__dict__["operations_client"] - - @property - def create_source( - self, - ) -> Callable[[securitycenter_service.CreateSourceRequest], gcs_source.Source]: - r"""Return a callable for the create source method over gRPC. - - Creates a source. - - Returns: - Callable[[~.CreateSourceRequest], - ~.Source]: - 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_source" not in self._stubs: - self._stubs["create_source"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateSource", - request_serializer=securitycenter_service.CreateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs["create_source"] - - @property - def create_finding( - self, - ) -> Callable[[securitycenter_service.CreateFindingRequest], gcs_finding.Finding]: - r"""Return a callable for the create finding method over gRPC. - - Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Returns: - Callable[[~.CreateFindingRequest], - ~.Finding]: - 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_finding" not in self._stubs: - self._stubs["create_finding"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateFinding", - request_serializer=securitycenter_service.CreateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs["create_finding"] - - @property - def create_notification_config( - self, - ) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - gcs_notification_config.NotificationConfig, - ]: - r"""Return a callable for the create notification config method over gRPC. - - Creates a notification config. - - Returns: - Callable[[~.CreateNotificationConfigRequest], - ~.NotificationConfig]: - 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_notification_config" not in self._stubs: - self._stubs["create_notification_config"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateNotificationConfig", - request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs["create_notification_config"] - - @property - def delete_notification_config( - self, - ) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], empty.Empty - ]: - r"""Return a callable for the delete notification config method over gRPC. - - Deletes a notification config. - - Returns: - Callable[[~.DeleteNotificationConfigRequest], - ~.Empty]: - 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 "delete_notification_config" not in self._stubs: - self._stubs["delete_notification_config"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/DeleteNotificationConfig", - request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, - response_deserializer=empty.Empty.FromString, - ) - return self._stubs["delete_notification_config"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy.GetIamPolicyRequest], policy.Policy]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the access control policy on the specified - Source. - - Returns: - Callable[[~.GetIamPolicyRequest], - ~.Policy]: - 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 "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetIamPolicy", - request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def get_notification_config( - self, - ) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - notification_config.NotificationConfig, - ]: - r"""Return a callable for the get notification config method over gRPC. - - Gets a notification config. - - Returns: - Callable[[~.GetNotificationConfigRequest], - ~.NotificationConfig]: - 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 "get_notification_config" not in self._stubs: - self._stubs["get_notification_config"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetNotificationConfig", - request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, - response_deserializer=notification_config.NotificationConfig.deserialize, - ) - return self._stubs["get_notification_config"] - - @property - def get_organization_settings( - self, - ) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - organization_settings.OrganizationSettings, - ]: - r"""Return a callable for the get organization settings method over gRPC. - - Gets the settings for an organization. - - Returns: - Callable[[~.GetOrganizationSettingsRequest], - ~.OrganizationSettings]: - 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 "get_organization_settings" not in self._stubs: - self._stubs["get_organization_settings"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetOrganizationSettings", - request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, - response_deserializer=organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs["get_organization_settings"] - - @property - def get_source( - self, - ) -> Callable[[securitycenter_service.GetSourceRequest], source.Source]: - r"""Return a callable for the get source method over gRPC. - - Gets a source. - - Returns: - Callable[[~.GetSourceRequest], - ~.Source]: - 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 "get_source" not in self._stubs: - self._stubs["get_source"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetSource", - request_serializer=securitycenter_service.GetSourceRequest.serialize, - response_deserializer=source.Source.deserialize, - ) - return self._stubs["get_source"] - - @property - def group_assets( - self, - ) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - securitycenter_service.GroupAssetsResponse, - ]: - r"""Return a callable for the group assets method over gRPC. - - Filters an organization's assets and groups them by - their specified properties. - - Returns: - Callable[[~.GroupAssetsRequest], - ~.GroupAssetsResponse]: - 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 "group_assets" not in self._stubs: - self._stubs["group_assets"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupAssets", - request_serializer=securitycenter_service.GroupAssetsRequest.serialize, - response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, - ) - return self._stubs["group_assets"] - - @property - def group_findings( - self, - ) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - securitycenter_service.GroupFindingsResponse, - ]: - r"""Return a callable for the group findings method over gRPC. - - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: - /v1p1beta1/organizations/{organization_id}/sources/-/findings - - Returns: - Callable[[~.GroupFindingsRequest], - ~.GroupFindingsResponse]: - 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 "group_findings" not in self._stubs: - self._stubs["group_findings"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupFindings", - request_serializer=securitycenter_service.GroupFindingsRequest.serialize, - response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, - ) - return self._stubs["group_findings"] - - @property - def list_assets( - self, - ) -> Callable[ - [securitycenter_service.ListAssetsRequest], - securitycenter_service.ListAssetsResponse, - ]: - r"""Return a callable for the list assets method over gRPC. - - Lists an organization's assets. - - Returns: - Callable[[~.ListAssetsRequest], - ~.ListAssetsResponse]: - 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 "list_assets" not in self._stubs: - self._stubs["list_assets"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListAssets", - request_serializer=securitycenter_service.ListAssetsRequest.serialize, - response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, - ) - return self._stubs["list_assets"] - - @property - def list_findings( - self, - ) -> Callable[ - [securitycenter_service.ListFindingsRequest], - securitycenter_service.ListFindingsResponse, - ]: - r"""Return a callable for the list findings method over gRPC. - - Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1p1beta1/organizations/{organization_id}/sources/-/findings - - Returns: - Callable[[~.ListFindingsRequest], - ~.ListFindingsResponse]: - 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 "list_findings" not in self._stubs: - self._stubs["list_findings"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListFindings", - request_serializer=securitycenter_service.ListFindingsRequest.serialize, - response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, - ) - return self._stubs["list_findings"] - - @property - def list_notification_configs( - self, - ) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - securitycenter_service.ListNotificationConfigsResponse, - ]: - r"""Return a callable for the list notification configs method over gRPC. - - Lists notification configs. - - Returns: - Callable[[~.ListNotificationConfigsRequest], - ~.ListNotificationConfigsResponse]: - 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 "list_notification_configs" not in self._stubs: - self._stubs["list_notification_configs"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListNotificationConfigs", - request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, - ) - return self._stubs["list_notification_configs"] - - @property - def list_sources( - self, - ) -> Callable[ - [securitycenter_service.ListSourcesRequest], - securitycenter_service.ListSourcesResponse, - ]: - r"""Return a callable for the list sources method over gRPC. - - Lists all sources belonging to an organization. - - Returns: - Callable[[~.ListSourcesRequest], - ~.ListSourcesResponse]: - 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 "list_sources" not in self._stubs: - self._stubs["list_sources"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListSources", - request_serializer=securitycenter_service.ListSourcesRequest.serialize, - response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, - ) - return self._stubs["list_sources"] - - @property - def run_asset_discovery( - self, - ) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], operations.Operation - ]: - r"""Return a callable for the run asset discovery method over gRPC. - - Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Returns: - Callable[[~.RunAssetDiscoveryRequest], - ~.Operation]: - 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 "run_asset_discovery" not in self._stubs: - self._stubs["run_asset_discovery"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/RunAssetDiscovery", - request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations.Operation.FromString, - ) - return self._stubs["run_asset_discovery"] - - @property - def set_finding_state( - self, - ) -> Callable[[securitycenter_service.SetFindingStateRequest], finding.Finding]: - r"""Return a callable for the set finding state method over gRPC. - - Updates the state of a finding. - - Returns: - Callable[[~.SetFindingStateRequest], - ~.Finding]: - 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 "set_finding_state" not in self._stubs: - self._stubs["set_finding_state"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/SetFindingState", - request_serializer=securitycenter_service.SetFindingStateRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs["set_finding_state"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], policy.Policy]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets the access control policy on the specified - Source. - - Returns: - Callable[[~.SetIamPolicyRequest], - ~.Policy]: - 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 "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/SetIamPolicy", - request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], iam_policy.TestIamPermissionsResponse - ]: - r"""Return a callable for the test iam permissions method over gRPC. - - Returns the permissions that a caller has on the - specified source. - - Returns: - Callable[[~.TestIamPermissionsRequest], - ~.TestIamPermissionsResponse]: - 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 "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/TestIamPermissions", - request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - @property - def update_finding( - self, - ) -> Callable[[securitycenter_service.UpdateFindingRequest], gcs_finding.Finding]: - r"""Return a callable for the update finding method over gRPC. - - Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Returns: - Callable[[~.UpdateFindingRequest], - ~.Finding]: - 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_finding" not in self._stubs: - self._stubs["update_finding"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateFinding", - request_serializer=securitycenter_service.UpdateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs["update_finding"] - - @property - def update_notification_config( - self, - ) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - gcs_notification_config.NotificationConfig, - ]: - r"""Return a callable for the update notification config method over gRPC. - - Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Returns: - Callable[[~.UpdateNotificationConfigRequest], - ~.NotificationConfig]: - 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_notification_config" not in self._stubs: - self._stubs["update_notification_config"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateNotificationConfig", - request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs["update_notification_config"] - - @property - def update_organization_settings( - self, - ) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - gcs_organization_settings.OrganizationSettings, - ]: - r"""Return a callable for the update organization settings method over gRPC. - - Updates an organization's settings. - - Returns: - Callable[[~.UpdateOrganizationSettingsRequest], - ~.OrganizationSettings]: - 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_organization_settings" not in self._stubs: - self._stubs["update_organization_settings"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateOrganizationSettings", - request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, - response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs["update_organization_settings"] - - @property - def update_source( - self, - ) -> Callable[[securitycenter_service.UpdateSourceRequest], gcs_source.Source]: - r"""Return a callable for the update source method over gRPC. - - Updates a source. - - Returns: - Callable[[~.UpdateSourceRequest], - ~.Source]: - 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_source" not in self._stubs: - self._stubs["update_source"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSource", - request_serializer=securitycenter_service.UpdateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs["update_source"] - - @property - def update_security_marks( - self, - ) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - gcs_security_marks.SecurityMarks, - ]: - r"""Return a callable for the update security marks method over gRPC. - - Updates security marks. - - Returns: - Callable[[~.UpdateSecurityMarksRequest], - ~.SecurityMarks]: - 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_security_marks" not in self._stubs: - self._stubs["update_security_marks"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSecurityMarks", - request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, - response_deserializer=gcs_security_marks.SecurityMarks.deserialize, - ) - return self._stubs["update_security_marks"] - - -__all__ = ("SecurityCenterGrpcTransport",) diff --git a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py b/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py deleted file mode 100644 index 4fcf66ec..00000000 --- a/google/cloud/securitycenter_v1p1beta1/services/security_center/transports/grpc_asyncio.py +++ /dev/null @@ -1,909 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple - -from google.api_core import grpc_helpers_async # type: ignore -from google.api_core import operations_v1 # type: ignore -from google.auth import credentials # type: ignore -from google.auth.transport.grpc import SslCredentials # type: ignore - -import grpc # type: ignore -from grpc.experimental import aio # type: ignore - -from google.cloud.securitycenter_v1p1beta1.types import finding -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import notification_config -from google.cloud.securitycenter_v1p1beta1.types import ( - notification_config as gcs_notification_config, -) -from google.cloud.securitycenter_v1p1beta1.types import organization_settings -from google.cloud.securitycenter_v1p1beta1.types import ( - organization_settings as gcs_organization_settings, -) -from google.cloud.securitycenter_v1p1beta1.types import ( - security_marks as gcs_security_marks, -) -from google.cloud.securitycenter_v1p1beta1.types import securitycenter_service -from google.cloud.securitycenter_v1p1beta1.types import source -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -from google.iam.v1 import iam_policy_pb2 as iam_policy # type: ignore -from google.iam.v1 import policy_pb2 as policy # type: ignore -from google.longrunning import operations_pb2 as operations # type: ignore -from google.protobuf import empty_pb2 as empty # type: ignore - -from .base import SecurityCenterTransport -from .grpc import SecurityCenterGrpcTransport - - -class SecurityCenterGrpcAsyncIOTransport(SecurityCenterTransport): - """gRPC AsyncIO backend transport for SecurityCenter. - - V1p1Beta1 APIs for Security Center service. - - 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 = "securitycenter.googleapis.com", - credentials: 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: - address (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]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional 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. - """ - scopes = scopes or cls.AUTH_SCOPES - return grpc_helpers_async.create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes, - quota_project_id=quota_project_id, - **kwargs, - ) - - def __init__( - self, - *, - host: str = "securitycenter.googleapis.com", - credentials: credentials.Credentials = None, - credentials_file: Optional[str] = None, - scopes: Optional[Sequence[str]] = None, - channel: aio.Channel = None, - api_mtls_endpoint: str = None, - client_cert_source: Callable[[], Tuple[bytes, bytes]] = None, - quota_project_id=None, - ) -> None: - """Instantiate the transport. - - Args: - host (Optional[str]): The hostname to connect to. - 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 ``channel`` is provided. - credentials_file (Optional[str]): A file with credentials that can - be loaded with :func:`google.auth.load_credentials_from_file`. - This argument is ignored if ``channel`` is provided. - scopes (Optional[Sequence[str]]): A optional 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[aio.Channel]): A ``Channel`` instance through - which to make calls. - api_mtls_endpoint (Optional[str]): 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 applicatin default SSL credentials. - client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 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. - quota_project_id (Optional[str]): An optional project to use for billing - and quota. - - 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. - """ - if channel: - # Sanity check: Ensure that channel and credentials are not both - # provided. - credentials = False - - # If a channel was explicitly provided, set it. - self._grpc_channel = channel - elif api_mtls_endpoint: - host = ( - api_mtls_endpoint - if ":" in api_mtls_endpoint - else api_mtls_endpoint + ":443" - ) - - # Create SSL credentials with client_cert_source or application - # default SSL credentials. - if client_cert_source: - cert, key = client_cert_source() - ssl_credentials = grpc.ssl_channel_credentials( - certificate_chain=cert, private_key=key - ) - else: - ssl_credentials = SslCredentials().ssl_credentials - - # create a new channel. The provided one is ignored. - self._grpc_channel = type(self).create_channel( - host, - credentials=credentials, - credentials_file=credentials_file, - ssl_credentials=ssl_credentials, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - ) - - # Run the base constructor. - super().__init__( - host=host, - credentials=credentials, - credentials_file=credentials_file, - scopes=scopes or self.AUTH_SCOPES, - quota_project_id=quota_project_id, - ) - - self._stubs = {} - - @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. - """ - # Sanity check: Only create a new channel if we do not already - # have one. - if not hasattr(self, "_grpc_channel"): - self._grpc_channel = self.create_channel( - self._host, credentials=self._credentials, - ) - - # Return the channel from cache. - return self._grpc_channel - - @property - def operations_client(self) -> operations_v1.OperationsAsyncClient: - """Create the client designed to process long-running operations. - - This property caches on the instance; repeated calls return the same - client. - """ - # Sanity check: Only create a new client if we do not already have one. - if "operations_client" not in self.__dict__: - self.__dict__["operations_client"] = operations_v1.OperationsAsyncClient( - self.grpc_channel - ) - - # Return the client from cache. - return self.__dict__["operations_client"] - - @property - def create_source( - self, - ) -> Callable[ - [securitycenter_service.CreateSourceRequest], Awaitable[gcs_source.Source] - ]: - r"""Return a callable for the create source method over gRPC. - - Creates a source. - - Returns: - Callable[[~.CreateSourceRequest], - Awaitable[~.Source]]: - 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_source" not in self._stubs: - self._stubs["create_source"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateSource", - request_serializer=securitycenter_service.CreateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs["create_source"] - - @property - def create_finding( - self, - ) -> Callable[ - [securitycenter_service.CreateFindingRequest], Awaitable[gcs_finding.Finding] - ]: - r"""Return a callable for the create finding method over gRPC. - - Creates a finding. The corresponding source must - exist for finding creation to succeed. - - Returns: - Callable[[~.CreateFindingRequest], - Awaitable[~.Finding]]: - 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_finding" not in self._stubs: - self._stubs["create_finding"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateFinding", - request_serializer=securitycenter_service.CreateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs["create_finding"] - - @property - def create_notification_config( - self, - ) -> Callable[ - [securitycenter_service.CreateNotificationConfigRequest], - Awaitable[gcs_notification_config.NotificationConfig], - ]: - r"""Return a callable for the create notification config method over gRPC. - - Creates a notification config. - - Returns: - Callable[[~.CreateNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - 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_notification_config" not in self._stubs: - self._stubs["create_notification_config"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/CreateNotificationConfig", - request_serializer=securitycenter_service.CreateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs["create_notification_config"] - - @property - def delete_notification_config( - self, - ) -> Callable[ - [securitycenter_service.DeleteNotificationConfigRequest], Awaitable[empty.Empty] - ]: - r"""Return a callable for the delete notification config method over gRPC. - - Deletes a notification config. - - Returns: - Callable[[~.DeleteNotificationConfigRequest], - Awaitable[~.Empty]]: - 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 "delete_notification_config" not in self._stubs: - self._stubs["delete_notification_config"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/DeleteNotificationConfig", - request_serializer=securitycenter_service.DeleteNotificationConfigRequest.serialize, - response_deserializer=empty.Empty.FromString, - ) - return self._stubs["delete_notification_config"] - - @property - def get_iam_policy( - self, - ) -> Callable[[iam_policy.GetIamPolicyRequest], Awaitable[policy.Policy]]: - r"""Return a callable for the get iam policy method over gRPC. - - Gets the access control policy on the specified - Source. - - Returns: - Callable[[~.GetIamPolicyRequest], - Awaitable[~.Policy]]: - 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 "get_iam_policy" not in self._stubs: - self._stubs["get_iam_policy"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetIamPolicy", - request_serializer=iam_policy.GetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, - ) - return self._stubs["get_iam_policy"] - - @property - def get_notification_config( - self, - ) -> Callable[ - [securitycenter_service.GetNotificationConfigRequest], - Awaitable[notification_config.NotificationConfig], - ]: - r"""Return a callable for the get notification config method over gRPC. - - Gets a notification config. - - Returns: - Callable[[~.GetNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - 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 "get_notification_config" not in self._stubs: - self._stubs["get_notification_config"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetNotificationConfig", - request_serializer=securitycenter_service.GetNotificationConfigRequest.serialize, - response_deserializer=notification_config.NotificationConfig.deserialize, - ) - return self._stubs["get_notification_config"] - - @property - def get_organization_settings( - self, - ) -> Callable[ - [securitycenter_service.GetOrganizationSettingsRequest], - Awaitable[organization_settings.OrganizationSettings], - ]: - r"""Return a callable for the get organization settings method over gRPC. - - Gets the settings for an organization. - - Returns: - Callable[[~.GetOrganizationSettingsRequest], - Awaitable[~.OrganizationSettings]]: - 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 "get_organization_settings" not in self._stubs: - self._stubs["get_organization_settings"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetOrganizationSettings", - request_serializer=securitycenter_service.GetOrganizationSettingsRequest.serialize, - response_deserializer=organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs["get_organization_settings"] - - @property - def get_source( - self, - ) -> Callable[[securitycenter_service.GetSourceRequest], Awaitable[source.Source]]: - r"""Return a callable for the get source method over gRPC. - - Gets a source. - - Returns: - Callable[[~.GetSourceRequest], - Awaitable[~.Source]]: - 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 "get_source" not in self._stubs: - self._stubs["get_source"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GetSource", - request_serializer=securitycenter_service.GetSourceRequest.serialize, - response_deserializer=source.Source.deserialize, - ) - return self._stubs["get_source"] - - @property - def group_assets( - self, - ) -> Callable[ - [securitycenter_service.GroupAssetsRequest], - Awaitable[securitycenter_service.GroupAssetsResponse], - ]: - r"""Return a callable for the group assets method over gRPC. - - Filters an organization's assets and groups them by - their specified properties. - - Returns: - Callable[[~.GroupAssetsRequest], - Awaitable[~.GroupAssetsResponse]]: - 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 "group_assets" not in self._stubs: - self._stubs["group_assets"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupAssets", - request_serializer=securitycenter_service.GroupAssetsRequest.serialize, - response_deserializer=securitycenter_service.GroupAssetsResponse.deserialize, - ) - return self._stubs["group_assets"] - - @property - def group_findings( - self, - ) -> Callable[ - [securitycenter_service.GroupFindingsRequest], - Awaitable[securitycenter_service.GroupFindingsResponse], - ]: - r"""Return a callable for the group findings method over gRPC. - - Filters an organization or source's findings and groups them by - their specified properties. - - To group across all sources provide a ``-`` as the source id. - Example: - /v1p1beta1/organizations/{organization_id}/sources/-/findings - - Returns: - Callable[[~.GroupFindingsRequest], - Awaitable[~.GroupFindingsResponse]]: - 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 "group_findings" not in self._stubs: - self._stubs["group_findings"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/GroupFindings", - request_serializer=securitycenter_service.GroupFindingsRequest.serialize, - response_deserializer=securitycenter_service.GroupFindingsResponse.deserialize, - ) - return self._stubs["group_findings"] - - @property - def list_assets( - self, - ) -> Callable[ - [securitycenter_service.ListAssetsRequest], - Awaitable[securitycenter_service.ListAssetsResponse], - ]: - r"""Return a callable for the list assets method over gRPC. - - Lists an organization's assets. - - Returns: - Callable[[~.ListAssetsRequest], - Awaitable[~.ListAssetsResponse]]: - 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 "list_assets" not in self._stubs: - self._stubs["list_assets"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListAssets", - request_serializer=securitycenter_service.ListAssetsRequest.serialize, - response_deserializer=securitycenter_service.ListAssetsResponse.deserialize, - ) - return self._stubs["list_assets"] - - @property - def list_findings( - self, - ) -> Callable[ - [securitycenter_service.ListFindingsRequest], - Awaitable[securitycenter_service.ListFindingsResponse], - ]: - r"""Return a callable for the list findings method over gRPC. - - Lists an organization or source's findings. - - To list across all sources provide a ``-`` as the source id. - Example: - /v1p1beta1/organizations/{organization_id}/sources/-/findings - - Returns: - Callable[[~.ListFindingsRequest], - Awaitable[~.ListFindingsResponse]]: - 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 "list_findings" not in self._stubs: - self._stubs["list_findings"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListFindings", - request_serializer=securitycenter_service.ListFindingsRequest.serialize, - response_deserializer=securitycenter_service.ListFindingsResponse.deserialize, - ) - return self._stubs["list_findings"] - - @property - def list_notification_configs( - self, - ) -> Callable[ - [securitycenter_service.ListNotificationConfigsRequest], - Awaitable[securitycenter_service.ListNotificationConfigsResponse], - ]: - r"""Return a callable for the list notification configs method over gRPC. - - Lists notification configs. - - Returns: - Callable[[~.ListNotificationConfigsRequest], - Awaitable[~.ListNotificationConfigsResponse]]: - 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 "list_notification_configs" not in self._stubs: - self._stubs["list_notification_configs"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListNotificationConfigs", - request_serializer=securitycenter_service.ListNotificationConfigsRequest.serialize, - response_deserializer=securitycenter_service.ListNotificationConfigsResponse.deserialize, - ) - return self._stubs["list_notification_configs"] - - @property - def list_sources( - self, - ) -> Callable[ - [securitycenter_service.ListSourcesRequest], - Awaitable[securitycenter_service.ListSourcesResponse], - ]: - r"""Return a callable for the list sources method over gRPC. - - Lists all sources belonging to an organization. - - Returns: - Callable[[~.ListSourcesRequest], - Awaitable[~.ListSourcesResponse]]: - 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 "list_sources" not in self._stubs: - self._stubs["list_sources"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/ListSources", - request_serializer=securitycenter_service.ListSourcesRequest.serialize, - response_deserializer=securitycenter_service.ListSourcesResponse.deserialize, - ) - return self._stubs["list_sources"] - - @property - def run_asset_discovery( - self, - ) -> Callable[ - [securitycenter_service.RunAssetDiscoveryRequest], - Awaitable[operations.Operation], - ]: - r"""Return a callable for the run asset discovery method over gRPC. - - Runs asset discovery. The discovery is tracked with a - long-running operation. - - This API can only be called with limited frequency for an - organization. If it is called too frequently the caller will - receive a TOO_MANY_REQUESTS error. - - Returns: - Callable[[~.RunAssetDiscoveryRequest], - Awaitable[~.Operation]]: - 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 "run_asset_discovery" not in self._stubs: - self._stubs["run_asset_discovery"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/RunAssetDiscovery", - request_serializer=securitycenter_service.RunAssetDiscoveryRequest.serialize, - response_deserializer=operations.Operation.FromString, - ) - return self._stubs["run_asset_discovery"] - - @property - def set_finding_state( - self, - ) -> Callable[ - [securitycenter_service.SetFindingStateRequest], Awaitable[finding.Finding] - ]: - r"""Return a callable for the set finding state method over gRPC. - - Updates the state of a finding. - - Returns: - Callable[[~.SetFindingStateRequest], - Awaitable[~.Finding]]: - 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 "set_finding_state" not in self._stubs: - self._stubs["set_finding_state"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/SetFindingState", - request_serializer=securitycenter_service.SetFindingStateRequest.serialize, - response_deserializer=finding.Finding.deserialize, - ) - return self._stubs["set_finding_state"] - - @property - def set_iam_policy( - self, - ) -> Callable[[iam_policy.SetIamPolicyRequest], Awaitable[policy.Policy]]: - r"""Return a callable for the set iam policy method over gRPC. - - Sets the access control policy on the specified - Source. - - Returns: - Callable[[~.SetIamPolicyRequest], - Awaitable[~.Policy]]: - 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 "set_iam_policy" not in self._stubs: - self._stubs["set_iam_policy"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/SetIamPolicy", - request_serializer=iam_policy.SetIamPolicyRequest.SerializeToString, - response_deserializer=policy.Policy.FromString, - ) - return self._stubs["set_iam_policy"] - - @property - def test_iam_permissions( - self, - ) -> Callable[ - [iam_policy.TestIamPermissionsRequest], - Awaitable[iam_policy.TestIamPermissionsResponse], - ]: - r"""Return a callable for the test iam permissions method over gRPC. - - Returns the permissions that a caller has on the - specified source. - - Returns: - Callable[[~.TestIamPermissionsRequest], - Awaitable[~.TestIamPermissionsResponse]]: - 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 "test_iam_permissions" not in self._stubs: - self._stubs["test_iam_permissions"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/TestIamPermissions", - request_serializer=iam_policy.TestIamPermissionsRequest.SerializeToString, - response_deserializer=iam_policy.TestIamPermissionsResponse.FromString, - ) - return self._stubs["test_iam_permissions"] - - @property - def update_finding( - self, - ) -> Callable[ - [securitycenter_service.UpdateFindingRequest], Awaitable[gcs_finding.Finding] - ]: - r"""Return a callable for the update finding method over gRPC. - - Creates or updates a finding. The corresponding - source must exist for a finding creation to succeed. - - Returns: - Callable[[~.UpdateFindingRequest], - Awaitable[~.Finding]]: - 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_finding" not in self._stubs: - self._stubs["update_finding"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateFinding", - request_serializer=securitycenter_service.UpdateFindingRequest.serialize, - response_deserializer=gcs_finding.Finding.deserialize, - ) - return self._stubs["update_finding"] - - @property - def update_notification_config( - self, - ) -> Callable[ - [securitycenter_service.UpdateNotificationConfigRequest], - Awaitable[gcs_notification_config.NotificationConfig], - ]: - r"""Return a callable for the update notification config method over gRPC. - - Updates a notification config. The following update fields are - allowed: description, pubsub_topic, streaming_config.filter - - Returns: - Callable[[~.UpdateNotificationConfigRequest], - Awaitable[~.NotificationConfig]]: - 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_notification_config" not in self._stubs: - self._stubs["update_notification_config"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateNotificationConfig", - request_serializer=securitycenter_service.UpdateNotificationConfigRequest.serialize, - response_deserializer=gcs_notification_config.NotificationConfig.deserialize, - ) - return self._stubs["update_notification_config"] - - @property - def update_organization_settings( - self, - ) -> Callable[ - [securitycenter_service.UpdateOrganizationSettingsRequest], - Awaitable[gcs_organization_settings.OrganizationSettings], - ]: - r"""Return a callable for the update organization settings method over gRPC. - - Updates an organization's settings. - - Returns: - Callable[[~.UpdateOrganizationSettingsRequest], - Awaitable[~.OrganizationSettings]]: - 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_organization_settings" not in self._stubs: - self._stubs["update_organization_settings"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateOrganizationSettings", - request_serializer=securitycenter_service.UpdateOrganizationSettingsRequest.serialize, - response_deserializer=gcs_organization_settings.OrganizationSettings.deserialize, - ) - return self._stubs["update_organization_settings"] - - @property - def update_source( - self, - ) -> Callable[ - [securitycenter_service.UpdateSourceRequest], Awaitable[gcs_source.Source] - ]: - r"""Return a callable for the update source method over gRPC. - - Updates a source. - - Returns: - Callable[[~.UpdateSourceRequest], - Awaitable[~.Source]]: - 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_source" not in self._stubs: - self._stubs["update_source"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSource", - request_serializer=securitycenter_service.UpdateSourceRequest.serialize, - response_deserializer=gcs_source.Source.deserialize, - ) - return self._stubs["update_source"] - - @property - def update_security_marks( - self, - ) -> Callable[ - [securitycenter_service.UpdateSecurityMarksRequest], - Awaitable[gcs_security_marks.SecurityMarks], - ]: - r"""Return a callable for the update security marks method over gRPC. - - Updates security marks. - - Returns: - Callable[[~.UpdateSecurityMarksRequest], - Awaitable[~.SecurityMarks]]: - 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_security_marks" not in self._stubs: - self._stubs["update_security_marks"] = self.grpc_channel.unary_unary( - "/google.cloud.securitycenter.v1p1beta1.SecurityCenter/UpdateSecurityMarks", - request_serializer=securitycenter_service.UpdateSecurityMarksRequest.serialize, - response_deserializer=gcs_security_marks.SecurityMarks.deserialize, - ) - return self._stubs["update_security_marks"] - - -__all__ = ("SecurityCenterGrpcAsyncIOTransport",) diff --git a/google/cloud/securitycenter_v1p1beta1/types/__init__.py b/google/cloud/securitycenter_v1p1beta1/types/__init__.py deleted file mode 100644 index c65c45b8..00000000 --- a/google/cloud/securitycenter_v1p1beta1/types/__init__.py +++ /dev/null @@ -1,95 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 .security_marks import SecurityMarks -from .asset import Asset -from .finding import Finding -from .notification_config import NotificationConfig -from .resource import Resource -from .notification_message import NotificationMessage -from .organization_settings import OrganizationSettings -from .run_asset_discovery_response import RunAssetDiscoveryResponse -from .source import Source -from .securitycenter_service import ( - CreateFindingRequest, - CreateNotificationConfigRequest, - CreateSourceRequest, - DeleteNotificationConfigRequest, - GetNotificationConfigRequest, - GetOrganizationSettingsRequest, - GetSourceRequest, - GroupAssetsRequest, - GroupAssetsResponse, - GroupFindingsRequest, - GroupFindingsResponse, - GroupResult, - ListNotificationConfigsRequest, - ListNotificationConfigsResponse, - ListSourcesRequest, - ListSourcesResponse, - ListAssetsRequest, - ListAssetsResponse, - ListFindingsRequest, - ListFindingsResponse, - SetFindingStateRequest, - RunAssetDiscoveryRequest, - UpdateFindingRequest, - UpdateNotificationConfigRequest, - UpdateOrganizationSettingsRequest, - UpdateSourceRequest, - UpdateSecurityMarksRequest, -) - - -__all__ = ( - "SecurityMarks", - "Asset", - "Finding", - "NotificationConfig", - "Resource", - "NotificationMessage", - "OrganizationSettings", - "RunAssetDiscoveryResponse", - "Source", - "CreateFindingRequest", - "CreateNotificationConfigRequest", - "CreateSourceRequest", - "DeleteNotificationConfigRequest", - "GetNotificationConfigRequest", - "GetOrganizationSettingsRequest", - "GetSourceRequest", - "GroupAssetsRequest", - "GroupAssetsResponse", - "GroupFindingsRequest", - "GroupFindingsResponse", - "GroupResult", - "ListNotificationConfigsRequest", - "ListNotificationConfigsResponse", - "ListSourcesRequest", - "ListSourcesResponse", - "ListAssetsRequest", - "ListAssetsResponse", - "ListFindingsRequest", - "ListFindingsResponse", - "SetFindingStateRequest", - "RunAssetDiscoveryRequest", - "UpdateFindingRequest", - "UpdateNotificationConfigRequest", - "UpdateOrganizationSettingsRequest", - "UpdateSourceRequest", - "UpdateSecurityMarksRequest", -) diff --git a/google/cloud/securitycenter_v1p1beta1/types/asset.py b/google/cloud/securitycenter_v1p1beta1/types/asset.py deleted file mode 100644 index 9d7f0742..00000000 --- a/google/cloud/securitycenter_v1p1beta1/types/asset.py +++ /dev/null @@ -1,168 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 proto # type: ignore - - -from google.cloud.securitycenter_v1p1beta1.types import ( - security_marks as gcs_security_marks, -) -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - - -__protobuf__ = proto.module( - package="google.cloud.securitycenter.v1p1beta1", manifest={"Asset",}, -) - - -class Asset(proto.Message): - r"""Security Command Center representation of a Google Cloud - resource. - - The Asset is a Security Command Center resource that captures - information about a single Google Cloud resource. All - modifications to an Asset are only within the context of - Security Command Center and don't affect the referenced Google - Cloud resource. - - Attributes: - name (str): - The relative resource name of this asset. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/assets/{asset_id}". - security_center_properties (~.asset.Asset.SecurityCenterProperties): - Security Command Center managed properties. - These properties are managed by Security Command - Center and cannot be modified by the user. - resource_properties (Sequence[~.asset.Asset.ResourcePropertiesEntry]): - Resource managed properties. These properties - are managed and defined by the Google Cloud - resource and cannot be modified by the user. - security_marks (~.gcs_security_marks.SecurityMarks): - User specified security marks. These marks - are entirely managed by the user and come from - the SecurityMarks resource that belongs to the - asset. - create_time (~.timestamp.Timestamp): - The time at which the asset was created in - Security Command Center. - update_time (~.timestamp.Timestamp): - The time at which the asset was last updated, - added, or deleted in Cloud SCC. - iam_policy (~.asset.Asset.IamPolicy): - Cloud IAM Policy information associated with - the Google Cloud resource described by the - Security Command Center asset. This information - is managed and defined by the Google Cloud - resource and cannot be modified by the user. - """ - - class SecurityCenterProperties(proto.Message): - r"""Security Command Center managed properties. These properties - are managed by Security Command Center and cannot be modified by - the user. - - Attributes: - resource_name (str): - The full resource name of the Google Cloud resource this - asset represents. This field is immutable after create time. - See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_type (str): - The type of the Google Cloud resource. - Examples include: APPLICATION, PROJECT, and - ORGANIZATION. This is a case insensitive field - defined by Security Command Center and/or the - producer of the resource and is immutable after - create time. - resource_parent (str): - The full resource name of the immediate parent of the - resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_project (str): - The full resource name of the project the resource belongs - to. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - resource_owners (Sequence[str]): - Owners of the Google Cloud resource. - resource_display_name (str): - The user defined display name for this - resource. - resource_parent_display_name (str): - The user defined display name for the parent - of this resource. - resource_project_display_name (str): - The user defined display name for the project - of this resource. - """ - - resource_name = proto.Field(proto.STRING, number=1) - - resource_type = proto.Field(proto.STRING, number=2) - - resource_parent = proto.Field(proto.STRING, number=3) - - resource_project = proto.Field(proto.STRING, number=4) - - resource_owners = proto.RepeatedField(proto.STRING, number=5) - - resource_display_name = proto.Field(proto.STRING, number=6) - - resource_parent_display_name = proto.Field(proto.STRING, number=7) - - resource_project_display_name = proto.Field(proto.STRING, number=8) - - class IamPolicy(proto.Message): - r"""Cloud IAM Policy information associated with the Google Cloud - resource described by the Security Command Center asset. This - information is managed and defined by the Google Cloud resource - and cannot be modified by the user. - - Attributes: - policy_blob (str): - The JSON representation of the Policy - associated with the asset. See - https://cloud.google.com/iam/docs/reference/rest/v1/Policy - for format details. - """ - - policy_blob = proto.Field(proto.STRING, number=1) - - name = proto.Field(proto.STRING, number=1) - - security_center_properties = proto.Field( - proto.MESSAGE, number=2, message=SecurityCenterProperties, - ) - - resource_properties = proto.MapField( - proto.STRING, proto.MESSAGE, number=7, message=struct.Value, - ) - - security_marks = proto.Field( - proto.MESSAGE, number=8, message=gcs_security_marks.SecurityMarks, - ) - - create_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) - - update_time = proto.Field(proto.MESSAGE, number=10, message=timestamp.Timestamp,) - - iam_policy = proto.Field(proto.MESSAGE, number=11, message=IamPolicy,) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/finding.py b/google/cloud/securitycenter_v1p1beta1/types/finding.py deleted file mode 100644 index 971aa3b4..00000000 --- a/google/cloud/securitycenter_v1p1beta1/types/finding.py +++ /dev/null @@ -1,125 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 proto # type: ignore - - -from google.cloud.securitycenter_v1p1beta1.types import ( - security_marks as gcs_security_marks, -) -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - - -__protobuf__ = proto.module( - package="google.cloud.securitycenter.v1p1beta1", manifest={"Finding",}, -) - - -class Finding(proto.Message): - r"""Security Command Center finding. - A finding is a record of assessment data (security, risk, health - or privacy) ingested into Security Command Center for - presentation, notification, analysis, policy testing, and - enforcement. For example, an XSS vulnerability in an App Engine - application is a finding. - - Attributes: - name (str): - The relative resource name of this finding. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}". - parent (str): - The relative resource name of the source the finding belongs - to. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - This field is immutable after creation time. For example: - "organizations/{organization_id}/sources/{source_id}". - resource_name (str): - For findings on Google Cloud resources, the full resource - name of the Google Cloud resource this finding is for. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - When the finding is for a non-Google Cloud resource, the - resourceName can be a customer or partner defined string. - This field is immutable after creation time. - state (~.finding.Finding.State): - The state of the finding. - category (str): - The additional taxonomy group within findings from a given - source. This field is immutable after creation time. - Example: "XSS_FLASH_INJECTION". - external_uri (str): - The URI that, if available, points to a web - page outside of Security Command Center where - additional information about the finding can be - found. This field is guaranteed to be either - empty or a well formed URL. - source_properties (Sequence[~.finding.Finding.SourcePropertiesEntry]): - Source specific properties. These properties are managed by - the source that writes the finding. The key names in the - source_properties map must be between 1 and 255 characters, - and must start with a letter and contain alphanumeric - characters or underscores only. - security_marks (~.gcs_security_marks.SecurityMarks): - Output only. User specified security marks. - These marks are entirely managed by the user and - come from the SecurityMarks resource that - belongs to the finding. - event_time (~.timestamp.Timestamp): - The time at which the event took place. For - example, if the finding represents an open - firewall it would capture the time the detector - believes the firewall became open. The accuracy - is determined by the detector. - create_time (~.timestamp.Timestamp): - The time at which the finding was created in - Security Command Center. - """ - - class State(proto.Enum): - r"""The state of the finding.""" - STATE_UNSPECIFIED = 0 - ACTIVE = 1 - INACTIVE = 2 - - name = proto.Field(proto.STRING, number=1) - - parent = proto.Field(proto.STRING, number=2) - - resource_name = proto.Field(proto.STRING, number=3) - - state = proto.Field(proto.ENUM, number=4, enum=State,) - - category = proto.Field(proto.STRING, number=5) - - external_uri = proto.Field(proto.STRING, number=6) - - source_properties = proto.MapField( - proto.STRING, proto.MESSAGE, number=7, message=struct.Value, - ) - - security_marks = proto.Field( - proto.MESSAGE, number=8, message=gcs_security_marks.SecurityMarks, - ) - - event_time = proto.Field(proto.MESSAGE, number=9, message=timestamp.Timestamp,) - - create_time = proto.Field(proto.MESSAGE, number=10, message=timestamp.Timestamp,) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/notification_config.py b/google/cloud/securitycenter_v1p1beta1/types/notification_config.py deleted file mode 100644 index 2be493b4..00000000 --- a/google/cloud/securitycenter_v1p1beta1/types/notification_config.py +++ /dev/null @@ -1,109 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 proto # type: ignore - - -__protobuf__ = proto.module( - package="google.cloud.securitycenter.v1p1beta1", manifest={"NotificationConfig",}, -) - - -class NotificationConfig(proto.Message): - r"""Security Command Center notification configs. - A notification config is a Security Command Center resource that - contains the configuration to send notifications for - create/update events of findings, assets and etc. - - Attributes: - name (str): - The relative resource name of this notification config. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/notificationConfigs/notify_public_bucket". - description (str): - The description of the notification config - (max of 1024 characters). - event_type (~.notification_config.NotificationConfig.EventType): - The type of events the config is for, e.g. - FINDING. - pubsub_topic (str): - The Pub/Sub topic to send notifications to. Its format is - "projects/[project_id]/topics/[topic]". - service_account (str): - Output only. The service account that needs - "pubsub.topics.publish" permission to publish to - the Pub/Sub topic. - streaming_config (~.notification_config.NotificationConfig.StreamingConfig): - The config for triggering streaming-based - notifications. - """ - - class EventType(proto.Enum): - r"""The type of events.""" - EVENT_TYPE_UNSPECIFIED = 0 - FINDING = 1 - - class StreamingConfig(proto.Message): - r"""The config for streaming-based notifications, which send each - event as soon as it is detected. - - Attributes: - filter (str): - Expression that defines the filter to apply across - create/update events of assets or findings as specified by - the event type. The expression is a list of zero or more - restrictions combined via logical operators ``AND`` and - ``OR``. Parentheses are supported, and ``OR`` has higher - precedence than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the - corresponding resource. - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - """ - - filter = proto.Field(proto.STRING, number=1) - - name = proto.Field(proto.STRING, number=1) - - description = proto.Field(proto.STRING, number=2) - - event_type = proto.Field(proto.ENUM, number=3, enum=EventType,) - - pubsub_topic = proto.Field(proto.STRING, number=4) - - service_account = proto.Field(proto.STRING, number=5) - - streaming_config = proto.Field( - proto.MESSAGE, number=6, oneof="notify_config", message=StreamingConfig, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/notification_message.py b/google/cloud/securitycenter_v1p1beta1/types/notification_message.py deleted file mode 100644 index 700d68eb..00000000 --- a/google/cloud/securitycenter_v1p1beta1/types/notification_message.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 proto # type: ignore - - -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import resource as gcs_resource - - -__protobuf__ = proto.module( - package="google.cloud.securitycenter.v1p1beta1", manifest={"NotificationMessage",}, -) - - -class NotificationMessage(proto.Message): - r"""Security Command Center's Notification - - Attributes: - notification_config_name (str): - Name of the notification config that - generated current notification. - finding (~.gcs_finding.Finding): - If it's a Finding based notification config, - this field will be populated. - resource (~.gcs_resource.Resource): - The Cloud resource tied to the notification. - """ - - notification_config_name = proto.Field(proto.STRING, number=1) - - finding = proto.Field( - proto.MESSAGE, number=2, oneof="event", message=gcs_finding.Finding, - ) - - resource = proto.Field(proto.MESSAGE, number=3, message=gcs_resource.Resource,) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py b/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py deleted file mode 100644 index 70fec686..00000000 --- a/google/cloud/securitycenter_v1p1beta1/types/organization_settings.py +++ /dev/null @@ -1,89 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 proto # type: ignore - - -__protobuf__ = proto.module( - package="google.cloud.securitycenter.v1p1beta1", manifest={"OrganizationSettings",}, -) - - -class OrganizationSettings(proto.Message): - r"""User specified settings that are attached to the Security - Command Center organization. - - Attributes: - name (str): - The relative resource name of the settings. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/organizationSettings". - enable_asset_discovery (bool): - A flag that indicates if Asset Discovery should be enabled. - If the flag is set to ``true``, then discovery of assets - will occur. If it is set to \`false, all historical assets - will remain, but discovery of future assets will not occur. - asset_discovery_config (~.organization_settings.OrganizationSettings.AssetDiscoveryConfig): - The configuration used for Asset Discovery - runs. - """ - - class AssetDiscoveryConfig(proto.Message): - r"""The configuration used for Asset Discovery runs. - - Attributes: - project_ids (Sequence[str]): - The project ids to use for filtering asset - discovery. - inclusion_mode (~.organization_settings.OrganizationSettings.AssetDiscoveryConfig.InclusionMode): - The mode to use for filtering asset - discovery. - """ - - class InclusionMode(proto.Enum): - r"""The mode of inclusion when running Asset Discovery. Asset discovery - can be limited by explicitly identifying projects to be included or - excluded. If INCLUDE_ONLY is set, then only those projects within - the organization and their children are discovered during asset - discovery. If EXCLUDE is set, then projects that don't match those - projects are discovered during asset discovery. If neither are set, - then all projects within the organization are discovered during - asset discovery. - """ - INCLUSION_MODE_UNSPECIFIED = 0 - INCLUDE_ONLY = 1 - EXCLUDE = 2 - - project_ids = proto.RepeatedField(proto.STRING, number=1) - - inclusion_mode = proto.Field( - proto.ENUM, - number=2, - enum="OrganizationSettings.AssetDiscoveryConfig.InclusionMode", - ) - - name = proto.Field(proto.STRING, number=1) - - enable_asset_discovery = proto.Field(proto.BOOL, number=2) - - asset_discovery_config = proto.Field( - proto.MESSAGE, number=3, message=AssetDiscoveryConfig, - ) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/resource.py b/google/cloud/securitycenter_v1p1beta1/types/resource.py deleted file mode 100644 index b29684ef..00000000 --- a/google/cloud/securitycenter_v1p1beta1/types/resource.py +++ /dev/null @@ -1,56 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 proto # type: ignore - - -__protobuf__ = proto.module( - package="google.cloud.securitycenter.v1p1beta1", manifest={"Resource",}, -) - - -class Resource(proto.Message): - r"""Information related to the Google Cloud resource. - - Attributes: - name (str): - The full resource name of the resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - project (str): - The full resource name of project that the - resource belongs to. - project_display_name (str): - The human readable name of project that the - resource belongs to. - parent (str): - The full resource name of resource's parent. - parent_display_name (str): - The human readable name of resource's parent. - """ - - name = proto.Field(proto.STRING, number=1) - - project = proto.Field(proto.STRING, number=2) - - project_display_name = proto.Field(proto.STRING, number=3) - - parent = proto.Field(proto.STRING, number=4) - - parent_display_name = proto.Field(proto.STRING, number=5) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py b/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py deleted file mode 100644 index 9c474a45..00000000 --- a/google/cloud/securitycenter_v1p1beta1/types/run_asset_discovery_response.py +++ /dev/null @@ -1,53 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 proto # type: ignore - - -from google.protobuf import duration_pb2 as gp_duration # type: ignore - - -__protobuf__ = proto.module( - package="google.cloud.securitycenter.v1p1beta1", - manifest={"RunAssetDiscoveryResponse",}, -) - - -class RunAssetDiscoveryResponse(proto.Message): - r"""Response of asset discovery run - - Attributes: - state (~.run_asset_discovery_response.RunAssetDiscoveryResponse.State): - The state of an asset discovery run. - duration (~.gp_duration.Duration): - The duration between asset discovery run - start and end - """ - - class State(proto.Enum): - r"""The state of an asset discovery run.""" - STATE_UNSPECIFIED = 0 - COMPLETED = 1 - SUPERSEDED = 2 - TERMINATED = 3 - - state = proto.Field(proto.ENUM, number=1, enum=State,) - - duration = proto.Field(proto.MESSAGE, number=2, message=gp_duration.Duration,) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/security_marks.py b/google/cloud/securitycenter_v1p1beta1/types/security_marks.py deleted file mode 100644 index a7671f48..00000000 --- a/google/cloud/securitycenter_v1p1beta1/types/security_marks.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 proto # type: ignore - - -__protobuf__ = proto.module( - package="google.cloud.securitycenter.v1p1beta1", manifest={"SecurityMarks",}, -) - - -class SecurityMarks(proto.Message): - r"""User specified security marks that are attached to the parent - Security Command Center resource. Security marks are scoped - within a Security Command Center organization -- they can be - modified and viewed by all users who have proper permissions on - the organization. - - Attributes: - name (str): - The relative resource name of the SecurityMarks. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Examples: - "organizations/{organization_id}/assets/{asset_id}/securityMarks" - "organizations/{organization_id}/sources/{source_id}/findings/{finding_id}/securityMarks". - marks (Sequence[~.security_marks.SecurityMarks.MarksEntry]): - Mutable user specified security marks belonging to the - parent resource. Constraints are as follows: - - - Keys and values are treated as case insensitive - - Keys must be between 1 - 256 characters (inclusive) - - Keys must be letters, numbers, underscores, or dashes - - Values have leading and trailing whitespace trimmed, - remaining characters must be between 1 - 4096 characters - (inclusive) - """ - - name = proto.Field(proto.STRING, number=1) - - marks = proto.MapField(proto.STRING, proto.STRING, number=2) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py b/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py deleted file mode 100644 index c4cf2b57..00000000 --- a/google/cloud/securitycenter_v1p1beta1/types/securitycenter_service.py +++ /dev/null @@ -1,1356 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 proto # type: ignore - - -from google.cloud.securitycenter_v1p1beta1.types import asset as gcs_asset -from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding -from google.cloud.securitycenter_v1p1beta1.types import ( - notification_config as gcs_notification_config, -) -from google.cloud.securitycenter_v1p1beta1.types import ( - organization_settings as gcs_organization_settings, -) -from google.cloud.securitycenter_v1p1beta1.types import ( - security_marks as gcs_security_marks, -) -from google.cloud.securitycenter_v1p1beta1.types import source as gcs_source -from google.protobuf import duration_pb2 as duration # type: ignore -from google.protobuf import field_mask_pb2 as gp_field_mask # type: ignore -from google.protobuf import struct_pb2 as struct # type: ignore -from google.protobuf import timestamp_pb2 as timestamp # type: ignore - - -__protobuf__ = proto.module( - package="google.cloud.securitycenter.v1p1beta1", - manifest={ - "CreateFindingRequest", - "CreateNotificationConfigRequest", - "CreateSourceRequest", - "DeleteNotificationConfigRequest", - "GetNotificationConfigRequest", - "GetOrganizationSettingsRequest", - "GetSourceRequest", - "GroupAssetsRequest", - "GroupAssetsResponse", - "GroupFindingsRequest", - "GroupFindingsResponse", - "GroupResult", - "ListNotificationConfigsRequest", - "ListNotificationConfigsResponse", - "ListSourcesRequest", - "ListSourcesResponse", - "ListAssetsRequest", - "ListAssetsResponse", - "ListFindingsRequest", - "ListFindingsResponse", - "SetFindingStateRequest", - "RunAssetDiscoveryRequest", - "UpdateFindingRequest", - "UpdateNotificationConfigRequest", - "UpdateOrganizationSettingsRequest", - "UpdateSourceRequest", - "UpdateSecurityMarksRequest", - }, -) - - -class CreateFindingRequest(proto.Message): - r"""Request message for creating a finding. - - Attributes: - parent (str): - Required. Resource name of the new finding's parent. Its - format should be - "organizations/[organization_id]/sources/[source_id]". - finding_id (str): - Required. Unique identifier provided by the - client within the parent scope. It must be - alphanumeric and less than or equal to 32 - characters and greater than 0 characters in - length. - finding (~.gcs_finding.Finding): - Required. The Finding being created. The name and - security_marks will be ignored as they are both output only - fields on this resource. - """ - - parent = proto.Field(proto.STRING, number=1) - - finding_id = proto.Field(proto.STRING, number=2) - - finding = proto.Field(proto.MESSAGE, number=3, message=gcs_finding.Finding,) - - -class CreateNotificationConfigRequest(proto.Message): - r"""Request message for creating a notification config. - - Attributes: - parent (str): - Required. Resource name of the new notification config's - parent. Its format is "organizations/[organization_id]". - config_id (str): - Required. - Unique identifier provided by the client within - the parent scope. It must be between 1 and 128 - characters, and contains alphanumeric - characters, underscores or hyphens only. - notification_config (~.gcs_notification_config.NotificationConfig): - Required. The notification config being - created. The name and the service account will - be ignored as they are both output only fields - on this resource. - """ - - parent = proto.Field(proto.STRING, number=1) - - config_id = proto.Field(proto.STRING, number=2) - - notification_config = proto.Field( - proto.MESSAGE, number=3, message=gcs_notification_config.NotificationConfig, - ) - - -class CreateSourceRequest(proto.Message): - r"""Request message for creating a source. - - Attributes: - parent (str): - Required. Resource name of the new source's parent. Its - format should be "organizations/[organization_id]". - source (~.gcs_source.Source): - Required. The Source being created, only the display_name - and description will be used. All other fields will be - ignored. - """ - - parent = proto.Field(proto.STRING, number=1) - - source = proto.Field(proto.MESSAGE, number=2, message=gcs_source.Source,) - - -class DeleteNotificationConfigRequest(proto.Message): - r"""Request message for deleting a notification config. - - Attributes: - name (str): - Required. Name of the notification config to delete. Its - format is - "organizations/[organization_id]/notificationConfigs/[config_id]". - """ - - name = proto.Field(proto.STRING, number=1) - - -class GetNotificationConfigRequest(proto.Message): - r"""Request message for getting a notification config. - - Attributes: - name (str): - Required. Name of the notification config to get. Its format - is - "organizations/[organization_id]/notificationConfigs/[config_id]". - """ - - name = proto.Field(proto.STRING, number=1) - - -class GetOrganizationSettingsRequest(proto.Message): - r"""Request message for getting organization settings. - - Attributes: - name (str): - Required. Name of the organization to get organization - settings for. Its format is - "organizations/[organization_id]/organizationSettings". - """ - - name = proto.Field(proto.STRING, number=1) - - -class GetSourceRequest(proto.Message): - r"""Request message for getting a source. - - Attributes: - name (str): - Required. Relative resource name of the source. Its format - is "organizations/[organization_id]/source/[source_id]". - """ - - name = proto.Field(proto.STRING, number=1) - - -class GroupAssetsRequest(proto.Message): - r"""Request message for grouping by assets. - - Attributes: - parent (str): - Required. Name of the organization to groupBy. Its format is - "organizations/[organization_id]". - filter (str): - Expression that defines the filter to apply across assets. - The expression is a list of zero or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the Asset - resource. Examples include: - - - name - - security_center_properties.resource_name - - resource_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``update_time = "2019-06-10T16:07:18-07:00"`` - ``update_time = 1560208038000`` - - - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``create_time = "2019-06-10T16:07:18-07:00"`` - ``create_time = 1560208038000`` - - - iam_policy.policy_blob: ``=``, ``:`` - - - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, - ``<=`` - - - security_marks.marks: ``=``, ``:`` - - - security_center_properties.resource_name: ``=``, ``:`` - - - security_center_properties.resource_name_display_name: - ``=``, ``:`` - - - security_center_properties.resource_type: ``=``, ``:`` - - - security_center_properties.resource_parent: ``=``, ``:`` - - - security_center_properties.resource_parent_display_name: - ``=``, ``:`` - - - security_center_properties.resource_project: ``=``, ``:`` - - - security_center_properties.resource_project_display_name: - ``=``, ``:`` - - - security_center_properties.resource_owners: ``=``, ``:`` - - For example, ``resource_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based on a - property existing: ``resource_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-resource_properties.my_property : ""`` - group_by (str): - Required. Expression that defines what assets fields to use - for grouping. The string value should follow SQL syntax: - comma separated list of fields. For example: - "security_center_properties.resource_project,security_center_properties.project". - - The following fields are supported when compare_duration is - not set: - - - security_center_properties.resource_project - - security_center_properties.resource_project_display_name - - security_center_properties.resource_type - - security_center_properties.resource_parent - - security_center_properties.resource_parent_display_name - - The following fields are supported when compare_duration is - set: - - - security_center_properties.resource_type - - security_center_properties.resource_project_display_name - - security_center_properties.resource_parent_display_name - compare_duration (~.duration.Duration): - When compare_duration is set, the GroupResult's - "state_change" property is updated to indicate whether the - asset was added, removed, or remained present during the - compare_duration period of time that precedes the read_time. - This is the time between (read_time - compare_duration) and - read_time. - - The state change value is derived based on the presence of - the asset at the two points in time. Intermediate state - changes between the two times don't affect the result. For - example, the results aren't affected if the asset is removed - and re-created again. - - Possible "state_change" values when compare_duration is - specified: - - - "ADDED": indicates that the asset was not present at the - start of compare_duration, but present at reference_time. - - "REMOVED": indicates that the asset was present at the - start of compare_duration, but not present at - reference_time. - - "ACTIVE": indicates that the asset was present at both - the start and the end of the time period defined by - compare_duration and reference_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all assets present at read_time. - - If this field is set then ``state_change`` must be a - specified field in ``group_by``. - read_time (~.timestamp.Timestamp): - Time used as a reference point when filtering - assets. The filter is limited to assets existing - at the supplied time and their values are those - at that specific time. Absence of this field - will default to the API's version of NOW. - page_token (str): - The value returned by the last ``GroupAssetsResponse``; - indicates that this is a continuation of a prior - ``GroupAssets`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - group_by = proto.Field(proto.STRING, number=3) - - compare_duration = proto.Field(proto.MESSAGE, number=4, message=duration.Duration,) - - read_time = proto.Field(proto.MESSAGE, number=5, message=timestamp.Timestamp,) - - page_token = proto.Field(proto.STRING, number=7) - - page_size = proto.Field(proto.INT32, number=8) - - -class GroupAssetsResponse(proto.Message): - r"""Response message for grouping by assets. - - Attributes: - group_by_results (Sequence[~.securitycenter_service.GroupResult]): - Group results. There exists an element for - each existing unique combination of - property/values. The element contains a count - for the number of times those specific - property/values appear. - read_time (~.timestamp.Timestamp): - Time used for executing the groupBy request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of results matching the - query. - """ - - @property - def raw_page(self): - return self - - group_by_results = proto.RepeatedField( - proto.MESSAGE, number=1, message="GroupResult", - ) - - read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - next_page_token = proto.Field(proto.STRING, number=3) - - total_size = proto.Field(proto.INT32, number=4) - - -class GroupFindingsRequest(proto.Message): - r"""Request message for grouping by findings. - - Attributes: - parent (str): - Required. Name of the source to groupBy. Its format is - "organizations/[organization_id]/sources/[source_id]". To - groupBy across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/- - filter (str): - Expression that defines the filter to apply across findings. - The expression is a list of one or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. Examples include: - - - name - - source_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - - name: ``=`` - - - parent: ``=``, ``:`` - - - resource_name: ``=``, ``:`` - - - state: ``=``, ``:`` - - - category: ``=``, ``:`` - - - external_uri: ``=``, ``:`` - - - event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``event_time = "2019-06-10T16:07:18-07:00"`` - ``event_time = 1560208038000`` - - - security_marks.marks: ``=``, ``:`` - - - source_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, - ``<=`` - - For example, ``source_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based on a - property existing: ``source_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-source_properties.my_property : ""`` - group_by (str): - Required. Expression that defines what assets fields to use - for grouping (including ``state_change``). The string value - should follow SQL syntax: comma separated list of fields. - For example: "parent,resource_name". - - The following fields are supported: - - - resource_name - - category - - state - - parent - - The following fields are supported when compare_duration is - set: - - - state_change - read_time (~.timestamp.Timestamp): - Time used as a reference point when filtering - findings. The filter is limited to findings - existing at the supplied time and their values - are those at that specific time. Absence of this - field will default to the API's version of NOW. - compare_duration (~.duration.Duration): - When compare_duration is set, the GroupResult's - "state_change" attribute is updated to indicate whether the - finding had its state changed, the finding's state remained - unchanged, or if the finding was added during the - compare_duration period of time that precedes the read_time. - This is the time between (read_time - compare_duration) and - read_time. - - The state_change value is derived based on the presence and - state of the finding at the two points in time. Intermediate - state changes between the two times don't affect the result. - For example, the results aren't affected if the finding is - made inactive and then active again. - - Possible "state_change" values when compare_duration is - specified: - - - "CHANGED": indicates that the finding was present and - matched the given filter at the start of - compare_duration, but changed its state at read_time. - - "UNCHANGED": indicates that the finding was present and - matched the given filter at the start of compare_duration - and did not change state at read_time. - - "ADDED": indicates that the finding did not match the - given filter or was not present at the start of - compare_duration, but was present at read_time. - - "REMOVED": indicates that the finding was present and - matched the filter at the start of compare_duration, but - did not match the filter at read_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all findings present at read_time. - - If this field is set then ``state_change`` must be a - specified field in ``group_by``. - page_token (str): - The value returned by the last ``GroupFindingsResponse``; - indicates that this is a continuation of a prior - ``GroupFindings`` call, and that the system should return - the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - group_by = proto.Field(proto.STRING, number=3) - - read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) - - compare_duration = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) - - page_token = proto.Field(proto.STRING, number=7) - - page_size = proto.Field(proto.INT32, number=8) - - -class GroupFindingsResponse(proto.Message): - r"""Response message for group by findings. - - Attributes: - group_by_results (Sequence[~.securitycenter_service.GroupResult]): - Group results. There exists an element for - each existing unique combination of - property/values. The element contains a count - for the number of times those specific - property/values appear. - read_time (~.timestamp.Timestamp): - Time used for executing the groupBy request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of results matching the - query. - """ - - @property - def raw_page(self): - return self - - group_by_results = proto.RepeatedField( - proto.MESSAGE, number=1, message="GroupResult", - ) - - read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - next_page_token = proto.Field(proto.STRING, number=3) - - total_size = proto.Field(proto.INT32, number=4) - - -class GroupResult(proto.Message): - r"""Result containing the properties and count of a groupBy - request. - - Attributes: - properties (Sequence[~.securitycenter_service.GroupResult.PropertiesEntry]): - Properties matching the groupBy fields in the - request. - count (int): - Total count of resources for the given - properties. - """ - - properties = proto.MapField( - proto.STRING, proto.MESSAGE, number=1, message=struct.Value, - ) - - count = proto.Field(proto.INT64, number=2) - - -class ListNotificationConfigsRequest(proto.Message): - r"""Request message for listing notification configs. - - Attributes: - parent (str): - Required. Name of the organization to list notification - configs. Its format is "organizations/[organization_id]". - page_token (str): - The value returned by the last - ``ListNotificationConfigsResponse``; indicates that this is - a continuation of a prior ``ListNotificationConfigs`` call, - and that the system should return the next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field(proto.STRING, number=1) - - page_token = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=3) - - -class ListNotificationConfigsResponse(proto.Message): - r"""Response message for listing notification configs. - - Attributes: - notification_configs (Sequence[~.gcs_notification_config.NotificationConfig]): - Notification configs belonging to the - requested parent. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - notification_configs = proto.RepeatedField( - proto.MESSAGE, number=1, message=gcs_notification_config.NotificationConfig, - ) - - next_page_token = proto.Field(proto.STRING, number=2) - - -class ListSourcesRequest(proto.Message): - r"""Request message for listing sources. - - Attributes: - parent (str): - Required. Resource name of the parent of sources to list. - Its format should be "organizations/[organization_id]". - page_token (str): - The value returned by the last ``ListSourcesResponse``; - indicates that this is a continuation of a prior - ``ListSources`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field(proto.STRING, number=1) - - page_token = proto.Field(proto.STRING, number=2) - - page_size = proto.Field(proto.INT32, number=7) - - -class ListSourcesResponse(proto.Message): - r"""Response message for listing sources. - - Attributes: - sources (Sequence[~.gcs_source.Source]): - Sources belonging to the requested parent. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - """ - - @property - def raw_page(self): - return self - - sources = proto.RepeatedField(proto.MESSAGE, number=1, message=gcs_source.Source,) - - next_page_token = proto.Field(proto.STRING, number=2) - - -class ListAssetsRequest(proto.Message): - r"""Request message for listing assets. - - Attributes: - parent (str): - Required. Name of the organization assets should belong to. - Its format is "organizations/[organization_id]". - filter (str): - Expression that defines the filter to apply across assets. - The expression is a list of zero or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. The fields map to those defined in the Asset - resource. Examples include: - - - name - - security_center_properties.resource_name - - resource_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following are the allowed field and operator - combinations: - - - name: ``=`` - - - update_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``update_time = "2019-06-10T16:07:18-07:00"`` - ``update_time = 1560208038000`` - - - create_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an - RFC3339 string. Examples: - ``create_time = "2019-06-10T16:07:18-07:00"`` - ``create_time = 1560208038000`` - - - iam_policy.policy_blob: ``=``, ``:`` - - - resource_properties: ``=``, ``:``, ``>``, ``<``, ``>=``, - ``<=`` - - - security_marks.marks: ``=``, ``:`` - - - security_center_properties.resource_name: ``=``, ``:`` - - - security_center_properties.resource_display_name: ``=``, - ``:`` - - - security_center_properties.resource_type: ``=``, ``:`` - - - security_center_properties.resource_parent: ``=``, ``:`` - - - security_center_properties.resource_parent_display_name: - ``=``, ``:`` - - - security_center_properties.resource_project: ``=``, ``:`` - - - security_center_properties.resource_project_display_name: - ``=``, ``:`` - - - security_center_properties.resource_owners: ``=``, ``:`` - - For example, ``resource_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based on a - property existing: ``resource_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-resource_properties.my_property : ""`` - order_by (str): - Expression that defines what fields and order to use for - sorting. The string value should follow SQL syntax: comma - separated list of fields. For example: - "name,resource_properties.a_property". The default sorting - order is ascending. To specify descending order for a field, - a suffix " desc" should be appended to the field name. For - example: "name desc,resource_properties.a_property". - Redundant space characters in the syntax are insignificant. - "name desc,resource_properties.a_property" and " name desc , - resource_properties.a_property " are equivalent. - - The following fields are supported: name update_time - resource_properties security_marks.marks - security_center_properties.resource_name - security_center_properties.resource_display_name - security_center_properties.resource_parent - security_center_properties.resource_parent_display_name - security_center_properties.resource_project - security_center_properties.resource_project_display_name - security_center_properties.resource_type - read_time (~.timestamp.Timestamp): - Time used as a reference point when filtering - assets. The filter is limited to assets existing - at the supplied time and their values are those - at that specific time. Absence of this field - will default to the API's version of NOW. - compare_duration (~.duration.Duration): - When compare_duration is set, the ListAssetsResult's - "state_change" attribute is updated to indicate whether the - asset was added, removed, or remained present during the - compare_duration period of time that precedes the read_time. - This is the time between (read_time - compare_duration) and - read_time. - - The state_change value is derived based on the presence of - the asset at the two points in time. Intermediate state - changes between the two times don't affect the result. For - example, the results aren't affected if the asset is removed - and re-created again. - - Possible "state_change" values when compare_duration is - specified: - - - "ADDED": indicates that the asset was not present at the - start of compare_duration, but present at read_time. - - "REMOVED": indicates that the asset was present at the - start of compare_duration, but not present at read_time. - - "ACTIVE": indicates that the asset was present at both - the start and the end of the time period defined by - compare_duration and read_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all assets present at read_time. - field_mask (~.gp_field_mask.FieldMask): - Optional. - A field mask to specify the ListAssetsResult - fields to be listed in the response. - An empty field mask will list all fields. - page_token (str): - The value returned by the last ``ListAssetsResponse``; - indicates that this is a continuation of a prior - ``ListAssets`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - order_by = proto.Field(proto.STRING, number=3) - - read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) - - compare_duration = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) - - field_mask = proto.Field(proto.MESSAGE, number=7, message=gp_field_mask.FieldMask,) - - page_token = proto.Field(proto.STRING, number=8) - - page_size = proto.Field(proto.INT32, number=9) - - -class ListAssetsResponse(proto.Message): - r"""Response message for listing assets. - - Attributes: - list_assets_results (Sequence[~.securitycenter_service.ListAssetsResponse.ListAssetsResult]): - Assets matching the list request. - read_time (~.timestamp.Timestamp): - Time used for executing the list request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of assets matching the - query. - """ - - class ListAssetsResult(proto.Message): - r"""Result containing the Asset and its State. - - Attributes: - asset (~.gcs_asset.Asset): - Asset matching the search request. - state_change (~.securitycenter_service.ListAssetsResponse.ListAssetsResult.StateChange): - State change of the asset between the points - in time. - """ - - class StateChange(proto.Enum): - r"""The change in state of the asset. - - When querying across two points in time this describes the change - between the two points: ADDED, REMOVED, or ACTIVE. If there was no - compare_duration supplied in the request the state change will be: - UNUSED - """ - UNUSED = 0 - ADDED = 1 - REMOVED = 2 - ACTIVE = 3 - - asset = proto.Field(proto.MESSAGE, number=1, message=gcs_asset.Asset,) - - state_change = proto.Field( - proto.ENUM, - number=2, - enum="ListAssetsResponse.ListAssetsResult.StateChange", - ) - - @property - def raw_page(self): - return self - - list_assets_results = proto.RepeatedField( - proto.MESSAGE, number=1, message=ListAssetsResult, - ) - - read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - next_page_token = proto.Field(proto.STRING, number=3) - - total_size = proto.Field(proto.INT32, number=4) - - -class ListFindingsRequest(proto.Message): - r"""Request message for listing findings. - - Attributes: - parent (str): - Required. Name of the source the findings belong to. Its - format is - "organizations/[organization_id]/sources/[source_id]". To - list across all sources provide a source_id of ``-``. For - example: organizations/{organization_id}/sources/- - filter (str): - Expression that defines the filter to apply across findings. - The expression is a list of one or more restrictions - combined via logical operators ``AND`` and ``OR``. - Parentheses are supported, and ``OR`` has higher precedence - than ``AND``. - - Restrictions have the form `` `` - and may have a ``-`` character in front of them to indicate - negation. Examples include: - - - name - - source_properties.a_property - - security_marks.marks.marka - - The supported operators are: - - - ``=`` for all value types. - - ``>``, ``<``, ``>=``, ``<=`` for integer values. - - ``:``, meaning substring matching, for strings. - - The supported value types are: - - - string literals in quotes. - - integer literals without quotes. - - boolean literals ``true`` and ``false`` without quotes. - - The following field and operator combinations are supported: - - name: ``=`` parent: ``=``, ``:`` resource_name: ``=``, ``:`` - state: ``=``, ``:`` category: ``=``, ``:`` external_uri: - ``=``, ``:`` event_time: ``=``, ``>``, ``<``, ``>=``, ``<=`` - - Usage: This should be milliseconds since epoch or an RFC3339 - string. Examples: - ``event_time = "2019-06-10T16:07:18-07:00"`` - ``event_time = 1560208038000`` - - security_marks.marks: ``=``, ``:`` source_properties: ``=``, - ``:``, ``>``, ``<``, ``>=``, ``<=`` - - For example, ``source_properties.size = 100`` is a valid - filter string. - - Use a partial match on the empty string to filter based on a - property existing: ``source_properties.my_property : ""`` - - Use a negated partial match on the empty string to filter - based on a property not existing: - ``-source_properties.my_property : ""`` - order_by (str): - Expression that defines what fields and order to use for - sorting. The string value should follow SQL syntax: comma - separated list of fields. For example: - "name,resource_properties.a_property". The default sorting - order is ascending. To specify descending order for a field, - a suffix " desc" should be appended to the field name. For - example: "name desc,source_properties.a_property". Redundant - space characters in the syntax are insignificant. "name - desc,source_properties.a_property" and " name desc , - source_properties.a_property " are equivalent. - - The following fields are supported: name parent state - category resource_name event_time source_properties - security_marks.marks - read_time (~.timestamp.Timestamp): - Time used as a reference point when filtering - findings. The filter is limited to findings - existing at the supplied time and their values - are those at that specific time. Absence of this - field will default to the API's version of NOW. - compare_duration (~.duration.Duration): - When compare_duration is set, the ListFindingsResult's - "state_change" attribute is updated to indicate whether the - finding had its state changed, the finding's state remained - unchanged, or if the finding was added in any state during - the compare_duration period of time that precedes the - read_time. This is the time between (read_time - - compare_duration) and read_time. - - The state_change value is derived based on the presence and - state of the finding at the two points in time. Intermediate - state changes between the two times don't affect the result. - For example, the results aren't affected if the finding is - made inactive and then active again. - - Possible "state_change" values when compare_duration is - specified: - - - "CHANGED": indicates that the finding was present and - matched the given filter at the start of - compare_duration, but changed its state at read_time. - - "UNCHANGED": indicates that the finding was present and - matched the given filter at the start of compare_duration - and did not change state at read_time. - - "ADDED": indicates that the finding did not match the - given filter or was not present at the start of - compare_duration, but was present at read_time. - - "REMOVED": indicates that the finding was present and - matched the filter at the start of compare_duration, but - did not match the filter at read_time. - - If compare_duration is not specified, then the only possible - state_change is "UNUSED", which will be the state_change set - for all findings present at read_time. - field_mask (~.gp_field_mask.FieldMask): - Optional. - A field mask to specify the Finding fields to be - listed in the response. An empty field mask will - list all fields. - page_token (str): - The value returned by the last ``ListFindingsResponse``; - indicates that this is a continuation of a prior - ``ListFindings`` call, and that the system should return the - next page of data. - page_size (int): - The maximum number of results to return in a - single response. Default is 10, minimum is 1, - maximum is 1000. - """ - - parent = proto.Field(proto.STRING, number=1) - - filter = proto.Field(proto.STRING, number=2) - - order_by = proto.Field(proto.STRING, number=3) - - read_time = proto.Field(proto.MESSAGE, number=4, message=timestamp.Timestamp,) - - compare_duration = proto.Field(proto.MESSAGE, number=5, message=duration.Duration,) - - field_mask = proto.Field(proto.MESSAGE, number=7, message=gp_field_mask.FieldMask,) - - page_token = proto.Field(proto.STRING, number=8) - - page_size = proto.Field(proto.INT32, number=9) - - -class ListFindingsResponse(proto.Message): - r"""Response message for listing findings. - - Attributes: - list_findings_results (Sequence[~.securitycenter_service.ListFindingsResponse.ListFindingsResult]): - Findings matching the list request. - read_time (~.timestamp.Timestamp): - Time used for executing the list request. - next_page_token (str): - Token to retrieve the next page of results, - or empty if there are no more results. - total_size (int): - The total number of findings matching the - query. - """ - - class ListFindingsResult(proto.Message): - r"""Result containing the Finding and its StateChange. - - Attributes: - finding (~.gcs_finding.Finding): - Finding matching the search request. - state_change (~.securitycenter_service.ListFindingsResponse.ListFindingsResult.StateChange): - State change of the finding between the - points in time. - resource (~.securitycenter_service.ListFindingsResponse.ListFindingsResult.Resource): - Output only. Resource that is associated with - this finding. - """ - - class StateChange(proto.Enum): - r"""The change in state of the finding. - - When querying across two points in time this describes the change in - the finding between the two points: CHANGED, UNCHANGED, ADDED, or - REMOVED. Findings can not be deleted, so REMOVED implies that the - finding at timestamp does not match the filter specified, but it did - at timestamp - compare_duration. If there was no compare_duration - supplied in the request the state change will be: UNUSED - """ - UNUSED = 0 - CHANGED = 1 - UNCHANGED = 2 - ADDED = 3 - REMOVED = 4 - - class Resource(proto.Message): - r"""Information related to the Google Cloud resource that is - associated with this finding. - - Attributes: - name (str): - The full resource name of the resource. See: - https://cloud.google.com/apis/design/resource_names#full_resource_name - project_name (str): - The full resource name of project that the - resource belongs to. - project_display_name (str): - The human readable name of project that the - resource belongs to. - parent_name (str): - The full resource name of resource's parent. - parent_display_name (str): - The human readable name of resource's parent. - """ - - name = proto.Field(proto.STRING, number=1) - - project_name = proto.Field(proto.STRING, number=2) - - project_display_name = proto.Field(proto.STRING, number=3) - - parent_name = proto.Field(proto.STRING, number=4) - - parent_display_name = proto.Field(proto.STRING, number=5) - - finding = proto.Field(proto.MESSAGE, number=1, message=gcs_finding.Finding,) - - state_change = proto.Field( - proto.ENUM, - number=2, - enum="ListFindingsResponse.ListFindingsResult.StateChange", - ) - - resource = proto.Field( - proto.MESSAGE, - number=3, - message="ListFindingsResponse.ListFindingsResult.Resource", - ) - - @property - def raw_page(self): - return self - - list_findings_results = proto.RepeatedField( - proto.MESSAGE, number=1, message=ListFindingsResult, - ) - - read_time = proto.Field(proto.MESSAGE, number=2, message=timestamp.Timestamp,) - - next_page_token = proto.Field(proto.STRING, number=3) - - total_size = proto.Field(proto.INT32, number=4) - - -class SetFindingStateRequest(proto.Message): - r"""Request message for updating a finding's state. - - Attributes: - name (str): - Required. The relative resource name of the finding. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}/finding/{finding_id}". - state (~.gcs_finding.Finding.State): - Required. The desired State of the finding. - start_time (~.timestamp.Timestamp): - Required. The time at which the updated state - takes effect. - """ - - name = proto.Field(proto.STRING, number=1) - - state = proto.Field(proto.ENUM, number=2, enum=gcs_finding.Finding.State,) - - start_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) - - -class RunAssetDiscoveryRequest(proto.Message): - r"""Request message for running asset discovery for an - organization. - - Attributes: - parent (str): - Required. Name of the organization to run asset discovery - for. Its format is "organizations/[organization_id]". - """ - - parent = proto.Field(proto.STRING, number=1) - - -class UpdateFindingRequest(proto.Message): - r"""Request message for updating or creating a finding. - - Attributes: - finding (~.gcs_finding.Finding): - Required. The finding resource to update or create if it - does not already exist. parent, security_marks, and - update_time will be ignored. - - In the case of creation, the finding id portion of the name - must be alphanumeric and less than or equal to 32 characters - and greater than 0 characters in length. - update_mask (~.gp_field_mask.FieldMask): - The FieldMask to use when updating the finding resource. - This field should not be specified when creating a finding. - - When updating a finding, an empty mask is treated as - updating all mutable fields and replacing source_properties. - Individual source_properties can be added/updated by using - "source_properties." in the field mask. - """ - - finding = proto.Field(proto.MESSAGE, number=1, message=gcs_finding.Finding,) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) - - -class UpdateNotificationConfigRequest(proto.Message): - r"""Request message for updating a notification config. - - Attributes: - notification_config (~.gcs_notification_config.NotificationConfig): - Required. The notification config to update. - update_mask (~.gp_field_mask.FieldMask): - The FieldMask to use when updating the - notification config. - If empty all mutable fields will be updated. - """ - - notification_config = proto.Field( - proto.MESSAGE, number=1, message=gcs_notification_config.NotificationConfig, - ) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) - - -class UpdateOrganizationSettingsRequest(proto.Message): - r"""Request message for updating an organization's settings. - - Attributes: - organization_settings (~.gcs_organization_settings.OrganizationSettings): - Required. The organization settings resource - to update. - update_mask (~.gp_field_mask.FieldMask): - The FieldMask to use when updating the - settings resource. - If empty all mutable fields will be updated. - """ - - organization_settings = proto.Field( - proto.MESSAGE, number=1, message=gcs_organization_settings.OrganizationSettings, - ) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) - - -class UpdateSourceRequest(proto.Message): - r"""Request message for updating a source. - - Attributes: - source (~.gcs_source.Source): - Required. The source resource to update. - update_mask (~.gp_field_mask.FieldMask): - The FieldMask to use when updating the source - resource. - If empty all mutable fields will be updated. - """ - - source = proto.Field(proto.MESSAGE, number=1, message=gcs_source.Source,) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) - - -class UpdateSecurityMarksRequest(proto.Message): - r"""Request message for updating a SecurityMarks resource. - - Attributes: - security_marks (~.gcs_security_marks.SecurityMarks): - Required. The security marks resource to - update. - update_mask (~.gp_field_mask.FieldMask): - The FieldMask to use when updating the security marks - resource. - - The field mask must not contain duplicate fields. If empty - or set to "marks", all marks will be replaced. Individual - marks can be updated using "marks.". - start_time (~.timestamp.Timestamp): - The time at which the updated SecurityMarks - take effect. If not set uses current server - time. Updates will be applied to the - SecurityMarks that are active immediately - preceding this time. - """ - - security_marks = proto.Field( - proto.MESSAGE, number=1, message=gcs_security_marks.SecurityMarks, - ) - - update_mask = proto.Field(proto.MESSAGE, number=2, message=gp_field_mask.FieldMask,) - - start_time = proto.Field(proto.MESSAGE, number=3, message=timestamp.Timestamp,) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/google/cloud/securitycenter_v1p1beta1/types/source.py b/google/cloud/securitycenter_v1p1beta1/types/source.py deleted file mode 100644 index 90a4ad7d..00000000 --- a/google/cloud/securitycenter_v1p1beta1/types/source.py +++ /dev/null @@ -1,64 +0,0 @@ -# -*- coding: utf-8 -*- - -# Copyright 2020 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 proto # type: ignore - - -__protobuf__ = proto.module( - package="google.cloud.securitycenter.v1p1beta1", manifest={"Source",}, -) - - -class Source(proto.Message): - r"""Security Command Center finding source. A finding source - is an entity or a mechanism that can produce a finding. A source - is like a container of findings that come from the same scanner, - logger, monitor, etc. - - Attributes: - name (str): - The relative resource name of this source. See: - https://cloud.google.com/apis/design/resource_names#relative_resource_name - Example: - "organizations/{organization_id}/sources/{source_id}". - display_name (str): - The source's display name. - A source's display name must be unique amongst - its siblings, for example, two sources with the - same parent can't share the same display name. - The display name must have a length between 1 - and 64 characters (inclusive). - description (str): - The description of the source (max of 1024 - characters). Example: - "Web Security Scanner is a web security scanner - for common vulnerabilities in App Engine - applications. It can automatically scan and - detect four common vulnerabilities, including - cross-site-scripting (XSS), Flash injection, - mixed content (HTTP in HTTPS), and - outdated/insecure libraries.". - """ - - name = proto.Field(proto.STRING, number=1) - - display_name = proto.Field(proto.STRING, number=2) - - description = proto.Field(proto.STRING, number=3) - - -__all__ = tuple(sorted(__protobuf__.manifest)) diff --git a/synth.metadata b/synth.metadata index 4f8baed8..3d13c815 100644 --- a/synth.metadata +++ b/synth.metadata @@ -4,7 +4,7 @@ "git": { "name": ".", "remote": "git@github.com:googleapis/python-securitycenter.git", - "sha": "6dcada9bc75d2d411ece89bd704adbaef1e94cfd" + "sha": "1cc4d1ffb5d64301d891d4ee95e429e4be1e4cf4" } }, { From 18132c7b35d859f339bc9ec8e3e3c59393773fd2 Mon Sep 17 00:00:00 2001 From: Bu Sun Kim Date: Thu, 10 Sep 2020 16:43:16 +0000 Subject: [PATCH 16/17] revert: revert changes to v1beta1 client resource helpers --- .../gapic/security_center_client.py | 37 +++++++++++-------- 1 file changed, 22 insertions(+), 15 deletions(-) diff --git a/google/cloud/securitycenter_v1beta1/gapic/security_center_client.py b/google/cloud/securitycenter_v1beta1/gapic/security_center_client.py index bc638425..72660006 100644 --- a/google/cloud/securitycenter_v1beta1/gapic/security_center_client.py +++ b/google/cloud/securitycenter_v1beta1/gapic/security_center_client.py @@ -89,6 +89,15 @@ def from_service_account_file(cls, filename, *args, **kwargs): from_service_account_json = from_service_account_file + @classmethod + def asset_security_marks_path(cls, organization, asset): + """Return a fully-qualified asset_security_marks string.""" + return google.api_core.path_template.expand( + "organizations/{organization}/assets/{asset}/securityMarks", + organization=organization, + asset=asset, + ) + @classmethod def finding_path(cls, organization, source, finding): """Return a fully-qualified finding string.""" @@ -99,6 +108,16 @@ def finding_path(cls, organization, source, finding): finding=finding, ) + @classmethod + def finding_security_marks_path(cls, organization, source, finding): + """Return a fully-qualified finding_security_marks string.""" + return google.api_core.path_template.expand( + "organizations/{organization}/sources/{source}/findings/{finding}/securityMarks", + organization=organization, + source=source, + finding=finding, + ) + @classmethod def organization_path(cls, organization): """Return a fully-qualified organization string.""" @@ -114,15 +133,6 @@ def organization_settings_path(cls, organization): organization=organization, ) - @classmethod - def security_marks_path(cls, organization, asset): - """Return a fully-qualified security_marks string.""" - return google.api_core.path_template.expand( - "organizations/{organization}/assets/{asset}/securityMarks", - organization=organization, - asset=asset, - ) - @classmethod def source_path(cls, organization, source): """Return a fully-qualified source string.""" @@ -431,8 +441,7 @@ def get_iam_policy( >>> >>> client = securitycenter_v1beta1.SecurityCenterClient() >>> - >>> # TODO: Initialize `resource`: - >>> resource = '' + >>> resource = client.source_path('[ORGANIZATION]', '[SOURCE]') >>> >>> response = client.get_iam_policy(resource) @@ -1638,8 +1647,7 @@ def set_iam_policy( >>> >>> client = securitycenter_v1beta1.SecurityCenterClient() >>> - >>> # TODO: Initialize `resource`: - >>> resource = '' + >>> resource = client.source_path('[ORGANIZATION]', '[SOURCE]') >>> >>> # TODO: Initialize `policy`: >>> policy = {} @@ -1720,8 +1728,7 @@ def test_iam_permissions( >>> >>> client = securitycenter_v1beta1.SecurityCenterClient() >>> - >>> # TODO: Initialize `resource`: - >>> resource = '' + >>> resource = client.source_path('[ORGANIZATION]', '[SOURCE]') >>> >>> # TODO: Initialize `permissions`: >>> permissions = [] From b2b36a221bc5f01b819b9c2cf845b4f8c51bd8f8 Mon Sep 17 00:00:00 2001 From: Bu Sun Kim Date: Thu, 10 Sep 2020 16:59:36 +0000 Subject: [PATCH 17/17] fix: add missing init files --- google/__init__.py | 24 ++++++++++++++++++++++++ google/cloud/__init__.py | 24 ++++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 google/__init__.py create mode 100644 google/cloud/__init__.py diff --git a/google/__init__.py b/google/__init__.py new file mode 100644 index 00000000..8fcc60e2 --- /dev/null +++ b/google/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2019 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. + +try: + import pkg_resources + + pkg_resources.declare_namespace(__name__) +except ImportError: + import pkgutil + + __path__ = pkgutil.extend_path(__path__, __name__) diff --git a/google/cloud/__init__.py b/google/cloud/__init__.py new file mode 100644 index 00000000..8fcc60e2 --- /dev/null +++ b/google/cloud/__init__.py @@ -0,0 +1,24 @@ +# -*- coding: utf-8 -*- +# +# Copyright 2019 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. + +try: + import pkg_resources + + pkg_resources.declare_namespace(__name__) +except ImportError: + import pkgutil + + __path__ = pkgutil.extend_path(__path__, __name__)