diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/securitycenter/snippets/AssetSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/securitycenter/snippets/AssetSnippets.java index 349b295980dd..a614ea12496e 100644 --- a/google-cloud-examples/src/main/java/com/google/cloud/examples/securitycenter/snippets/AssetSnippets.java +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/securitycenter/snippets/AssetSnippets.java @@ -5,7 +5,7 @@ * 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, @@ -15,14 +15,20 @@ */ package com.google.cloud.examples.securitycenter.snippets; -import com.google.cloud.securitycenter.v1beta1.ListAssetsRequest; -import com.google.cloud.securitycenter.v1beta1.ListAssetsResponse.ListAssetsResult; -import com.google.cloud.securitycenter.v1beta1.OrganizationName; -import com.google.cloud.securitycenter.v1beta1.SecurityCenterClient; -import com.google.cloud.securitycenter.v1beta1.SecurityCenterClient.ListAssetsPagedResponse; +import com.google.api.gax.longrunning.OperationFuture; +import com.google.api.gax.rpc.ResourceExhaustedException; +import com.google.cloud.securitycenter.v1.GroupAssetsRequest; +import com.google.cloud.securitycenter.v1.GroupResult; +import com.google.cloud.securitycenter.v1.ListAssetsRequest; +import com.google.cloud.securitycenter.v1.ListAssetsResponse.ListAssetsResult; +import com.google.cloud.securitycenter.v1.OrganizationName; +import com.google.cloud.securitycenter.v1.SecurityCenterClient; +import com.google.cloud.securitycenter.v1.SecurityCenterClient.GroupAssetsPagedResponse; +import com.google.cloud.securitycenter.v1.SecurityCenterClient.ListAssetsPagedResponse; import com.google.common.base.MoreObjects; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; +import com.google.protobuf.Empty; import java.io.IOException; import org.threeten.bp.Duration; import org.threeten.bp.Instant; @@ -40,7 +46,7 @@ private AssetSnippets() {} static ImmutableList listAssets(OrganizationName organizationName) { try (SecurityCenterClient client = SecurityCenterClient.create()) { // Start setting up a request for to search for all assets in an organization. - // OrganizationName organizationName = OrganizationName.of("123234324"); + // OrganizationName organizationName = OrganizationName.of(/*organizationId=*/"123234324"); ListAssetsRequest.Builder request = ListAssetsRequest.newBuilder().setParent(organizationName.toString()); @@ -48,7 +54,7 @@ static ImmutableList listAssets(OrganizationName organizationN ListAssetsPagedResponse response = client.listAssets(request.build()); // This creates one list for all assets. If your organization has a large number of assets - // this can cause out of memory issues. You can process them batches by returning + // this can cause out of memory issues. You can process them incrementally by returning // the Iterable returned response.iterateAll() directly. ImmutableList results = ImmutableList.copyOf(response.iterateAll()); System.out.println("All assets:"); @@ -69,22 +75,21 @@ static ImmutableList listAssets(OrganizationName organizationN static ImmutableList listAssetsWithFilter(OrganizationName organizationName) { try (SecurityCenterClient client = SecurityCenterClient.create()) { // Start setting up a request for to search for all assets in an organization. - // OrganizationName organizationName = OrganizationName.of("123234324"); - ListAssetsRequest request = + // OrganizationName organizationName = OrganizationName.of(/*organizationId=*/"123234324"); + ListAssetsRequest.Builder request = ListAssetsRequest.newBuilder() .setParent(organizationName.toString()) .setFilter( - "security_center_properties.resource_type=\"google.cloud.resourcemanager.Project\"") - .build(); + "security_center_properties.resource_type=\"google.cloud.resourcemanager.Project\""); // Call the API. - ListAssetsPagedResponse response = client.listAssets(request); + ListAssetsPagedResponse response = client.listAssets(request.build()); // This creates one list for all assets. If your organization has a large number of assets - // this can cause out of memory issues. You can process them batches by returning + // this can cause out of memory issues. You can process them incrementally by returning // the Iterable returned response.iterateAll() directly. ImmutableList results = ImmutableList.copyOf(response.iterateAll()); - System.out.println("Projects:"); + System.out.println("Project assets:"); System.out.println(results); return results; } catch (IOException e) { @@ -104,7 +109,7 @@ static ImmutableList listAssetsAsOfYesterday( OrganizationName organizationName, Instant asOf) { try (SecurityCenterClient client = SecurityCenterClient.create()) { // Start setting up a request for to search for all assets in an organization. - // OrganizationName organizationName = OrganizationName.of("123234324"); + // OrganizationName organizationName = OrganizationName.of(/*organizationId=*/"123234324"); // Initialize the builder with the organization and filter ListAssetsRequest.Builder request = @@ -121,7 +126,7 @@ static ImmutableList listAssetsAsOfYesterday( ListAssetsPagedResponse response = client.listAssets(request.build()); // This creates one list for all assets. If your organization has a large number of assets - // this can cause out of memory issues. You can process them batches by returning + // this can cause out of memory issues. You can process them incrementally by returning // the Iterable returned response.iterateAll() directly. ImmutableList results = ImmutableList.copyOf(response.iterateAll()); System.out.println("Projects:"); @@ -146,7 +151,7 @@ static ImmutableList listAssetAndStatusChanges( try (SecurityCenterClient client = SecurityCenterClient.create()) { // Start setting up a request for to search for all assets in an organization. - // OrganizationName organizationName = OrganizationName.of("123234324"); + // OrganizationName organizationName = OrganizationName.of(/*organizationId=*/"123234324"); ListAssetsRequest.Builder request = ListAssetsRequest.newBuilder() .setParent(organizationName.toString()) @@ -165,7 +170,7 @@ static ImmutableList listAssetAndStatusChanges( ListAssetsPagedResponse response = client.listAssets(request.build()); // This creates one list for all assets. If your organization has a large number of assets - // this can cause out of memory issues. You can process them batches by returning + // this can cause out of memory issues. You can process them incrementally by returning // the Iterable returned response.iterateAll() directly. ImmutableList results = ImmutableList.copyOf(response.iterateAll()); System.out.println("Projects:"); @@ -177,6 +182,129 @@ static ImmutableList listAssetAndStatusChanges( } // [END list_asset_changes_status_changes] + /** + * Groups all assets by their specified properties (e.g. type) for an organization. + * + * @param organizationName The organization to group assets for. + */ + // [START group_all_assets] + static ImmutableList groupAssets(OrganizationName organizationName) { + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // Start setting up a request for to group all assets by type in an organization. + // OrganizationName organizationName = OrganizationName.of("123234324"); + GroupAssetsRequest.Builder request = + GroupAssetsRequest.newBuilder() + .setGroupBy("security_center_properties.resource_type") + .setParent(organizationName.toString()); + + // Call the API. + GroupAssetsPagedResponse response = client.groupAssets(request.build()); + + // This creates one list for all assets. If your organization has a large number of assets + // this can cause out of memory issues. You can process them batches by returning + // the Iterable returned response.iterateAll() directly. + ImmutableList results = ImmutableList.copyOf(response.iterateAll()); + System.out.println("All assets:"); + System.out.println(results); + return results; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END group_all_assets] + + /** + * Filters all assets by their specified properties and groups them by specified properties for an + * organization. + * + * @param organizationName The organization to group assets for. + */ + // [START group_all_assets_with_filter] + static ImmutableList groupAssetsWithFilter(OrganizationName organizationName) { + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // Start setting up a request for to filter all assets by type and group them by project in an + // organization. + // OrganizationName organizationName = OrganizationName.of("123234324"); + GroupAssetsRequest.Builder request = + GroupAssetsRequest.newBuilder() + .setFilter( + "security_center_properties.resource_type=\"google.cloud.resourcemanager.Project\"") + .setGroupBy("security_center_properties.resource_project") + .setParent(organizationName.toString()); + + // Call the API. + GroupAssetsPagedResponse response = client.groupAssets(request.build()); + + // This creates one list for all assets. If your organization has a large number of assets + // this can cause out of memory issues. You can process them batches by returning + // the Iterable returned response.iterateAll() directly. + ImmutableList results = ImmutableList.copyOf(response.iterateAll()); + System.out.println("All assets:"); + System.out.println(results); + return results; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END group_all_assets_with_filter] + + /** + * Groups all assets by their state_changes (ADDED/DELETED/ACTIVE) during a period of time for an + * organization. + * + * @param organizationName The organization to group assets for. + */ + // [START group_all_assets_with_compare_duration] + static ImmutableList groupAssetsWithCompareDuration( + OrganizationName organizationName, Duration duration) { + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // Start setting up a request for to group all assets during a period of time in an + // organization. + // OrganizationName organizationName = OrganizationName.of("123234324"); + GroupAssetsRequest.Builder request = + GroupAssetsRequest.newBuilder() + .setGroupBy("state_change") + .setParent(organizationName.toString()); + request + .getCompareDurationBuilder() + .setSeconds(duration.getSeconds()) + .setNanos(duration.getNano()); + + // Call the API. + GroupAssetsPagedResponse response = client.groupAssets(request.build()); + + // This creates one list for all assets. If your organization has a large number of assets + // this can cause out of memory issues. You can process them batches by returning + // the Iterable returned response.iterateAll() directly. + ImmutableList results = ImmutableList.copyOf(response.iterateAll()); + System.out.println("All assets:"); + System.out.println(results); + return results; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END group_all_assets_with_compare_duration] + + // [START run_asset_discovery] + static void runAssetDiscovery(OrganizationName organizationName) { + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // Call the API. Note calls to runAssetDiscovery are throttled if too many requests + // are made. + OperationFuture result = client.runAssetDiscoveryAsync(organizationName); + + // Uncomment this line to wait for a certain amount of time for the asset discovery run + // to complete. + // result.get(130, TimeUnit.SECONDS); + System.out.println("Asset discovery runs asynchronously."); + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } catch (ResourceExhaustedException e) { + System.out.println("Asset discovery run already in progress."); + } + } + // [END run_asset_discovery] + public static void main(String... args) { String org_id = System.getenv("ORGANIZATION_ID"); if (args.length > 0) { diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/securitycenter/snippets/FindingSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/securitycenter/snippets/FindingSnippets.java new file mode 100644 index 000000000000..4980aa54205a --- /dev/null +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/securitycenter/snippets/FindingSnippets.java @@ -0,0 +1,532 @@ +/* + * 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. + */ +package com.google.cloud.examples.securitycenter.snippets; + +import com.google.cloud.securitycenter.v1.Finding; +import com.google.cloud.securitycenter.v1.Finding.State; +import com.google.cloud.securitycenter.v1.FindingName; +import com.google.cloud.securitycenter.v1.GroupFindingsRequest; +import com.google.cloud.securitycenter.v1.GroupResult; +import com.google.cloud.securitycenter.v1.ListFindingsRequest; +import com.google.cloud.securitycenter.v1.ListFindingsResponse.ListFindingsResult; +import com.google.cloud.securitycenter.v1.OrganizationName; +import com.google.cloud.securitycenter.v1.SecurityCenterClient; +import com.google.cloud.securitycenter.v1.SecurityCenterClient.GroupFindingsPagedResponse; +import com.google.cloud.securitycenter.v1.SecurityCenterClient.ListFindingsPagedResponse; +import com.google.cloud.securitycenter.v1.SourceName; +import com.google.cloud.securitycenter.v1.UpdateFindingRequest; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.iam.v1.TestIamPermissionsResponse; +import com.google.protobuf.FieldMask; +import com.google.protobuf.Timestamp; +import com.google.protobuf.Value; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import org.threeten.bp.Duration; +import org.threeten.bp.Instant; + +/** Snippets for how to work with Findings in Cloud Security Command Center. */ +public class FindingSnippets { + private FindingSnippets() {} + + /** + * Create a finding under a source. + * + * @param sourceName The source for the finding. + */ + // [START create_finding] + static Finding createFinding(SourceName sourceName, String findingId) { + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // SourceName sourceName = SourceName.of(/*organization=*/"123234324",/*source=*/ + // "423432321"); + // String findingId = "samplefindingid"; + + // Use the current time as the finding "event time". + Instant eventTime = Instant.now(); + + // The resource this finding applies to. The CSCC UI can link + // the findings for a resource to the corresponding Asset of a resource + // if there are matches. + String resourceName = "//cloudresourcemanager.googleapis.com/organizations/11232"; + + // Start setting up a request to create a finding in a source. + Finding finding = + Finding.newBuilder() + .setParent(sourceName.toString()) + .setState(State.ACTIVE) + .setResourceName(resourceName) + .setEventTime( + Timestamp.newBuilder() + .setSeconds(eventTime.getEpochSecond()) + .setNanos(eventTime.getNano())) + .setCategory("MEDIUM_RISK_ONE") + .build(); + + // Call the API. + Finding response = client.createFinding(sourceName, findingId, finding); + + System.out.println("Created Finding: " + response); + return response; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END create_finding] + + /** + * Create a finding with source properties under a source. + * + * @param sourceName The source for the finding. + */ + // [START create_finding_with_source_properties] + static Finding createFindingWithSourceProperties(SourceName sourceName) { + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // SourceName sourceName = SourceName.of(/*organization=*/"123234324",/*source=*/ + // "423432321"); + + // Use the current time as the finding "event time". + Instant eventTime = Instant.now(); + + // Controlled by caller. + String findingId = "samplefindingid2"; + + // The resource this finding applies to. The CSCC UI can link + // the findings for a resource to the corresponding Asset of a resource + // if there are matches. + String resourceName = "//cloudresourcemanager.googleapis.com/organizations/11232"; + + // Define source properties values as protobuf "Value" objects. + Value stringValue = Value.newBuilder().setStringValue("stringExample").build(); + Value numValue = Value.newBuilder().setNumberValue(1234).build(); + ImmutableMap sourceProperties = + ImmutableMap.of("stringKey", stringValue, "numKey", numValue); + + // Start setting up a request to create a finding in a source. + Finding finding = + Finding.newBuilder() + .setParent(sourceName.toString()) + .setState(State.ACTIVE) + .setResourceName(resourceName) + .setEventTime( + Timestamp.newBuilder() + .setSeconds(eventTime.getEpochSecond()) + .setNanos(eventTime.getNano())) + .putAllSourceProperties(sourceProperties) + .build(); + + // Call the API. + Finding response = client.createFinding(sourceName, findingId, finding); + + System.out.println("Created Finding with Source Properties: " + response); + return response; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END create_finding_with_source_properties] + + /** + * Update a finding's source properties. + * + * @param findingName The finding to update. + */ + // [START update_finding] + static Finding updateFinding(FindingName findingName) { + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // FindingName findingName = FindingName.of(/*organization=*/"123234324", + // /*source=*/"423432321", /*findingId=*/"samplefindingid2"); + + // Use the current time as the finding "event time". + Instant eventTime = Instant.now(); + + // Define source properties values as protobuf "Value" objects. + Value stringValue = Value.newBuilder().setStringValue("value").build(); + + FieldMask updateMask = + FieldMask.newBuilder() + .addPaths("event_time") + .addPaths("source_properties.stringKey") + .build(); + + Finding finding = + Finding.newBuilder() + .setName(findingName.toString()) + .setEventTime( + Timestamp.newBuilder() + .setSeconds(eventTime.getEpochSecond()) + .setNanos(eventTime.getNano())) + .putSourceProperties("stringKey", stringValue) + .build(); + + UpdateFindingRequest.Builder request = + UpdateFindingRequest.newBuilder().setFinding(finding).setUpdateMask(updateMask); + + // Call the API. + Finding response = client.updateFinding(request.build()); + + System.out.println("Updated Finding: " + response); + return response; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END update_finding] + + /** + * Updates a finding's state to INACTIVE. + * + * @param findingName The finding to update. + */ + // [START update_finding_state] + static Finding setFindingState(FindingName findingName) { + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // FindingName findingName = FindingName.of(/*organization=*/"123234324", + // /*source=*/"423432321", /*findingId=*/"samplefindingid2"); + + // Use the current time as the finding "event time". + Instant eventTime = Instant.now(); + + Finding response = + client.setFindingState( + findingName, + State.INACTIVE, + Timestamp.newBuilder() + .setSeconds(eventTime.getEpochSecond()) + .setNanos(eventTime.getNano()) + .build()); + + System.out.println("Updated Finding: " + response); + return response; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END update_finding_state] + + /** + * List all findings under an organization. + * + * @param organizationName The source to list all findings for. + */ + // [START list_all_findings] + static ImmutableList listAllFindings(OrganizationName organizationName) { + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // OrganizationName organizationName = OrganizationName.of(/*organizationId=*/"123234324"); + // "-" Indicates listing across all sources. + SourceName sourceName = SourceName.of(organizationName.getOrganization(), "-"); + + ListFindingsRequest.Builder request = + ListFindingsRequest.newBuilder().setParent(sourceName.toString()); + + // Call the API. + ListFindingsPagedResponse response = client.listFindings(request.build()); + + // This creates one list for all findings. If your organization has a large number of + // findings this can cause out of memory issues. You can process them in incrementally + // by returning the Iterable returned response.iterateAll() directly. + ImmutableList results = ImmutableList.copyOf(response.iterateAll()); + System.out.println("Findings:"); + System.out.println(results); + return results; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END list_all_findings] + + /** + * List filtered findings under a source. + * + * @param sourceName The source to list filtered findings for. + */ + // [START list_filtered_findings] + static ImmutableList listFilteredFindings(SourceName sourceName) { + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // SourceName sourceName = SourceName.of(/*organizationId=*/"123234324", + // /*sourceId=*/"423432321"); + + // Create filter to category of MEDIUM_RISK_ONE + String filter = "category=\"MEDIUM_RISK_ONE\""; + + ListFindingsRequest.Builder request = + ListFindingsRequest.newBuilder().setParent(sourceName.toString()).setFilter(filter); + + // Call the API. + ListFindingsPagedResponse response = client.listFindings(request.build()); + + // This creates one list for all findings. If your organization has a large number of + // findings this can cause out of memory issues. You can process them in incrementally + // by returning the Iterable returned response.iterateAll() directly. + ImmutableList results = ImmutableList.copyOf(response.iterateAll()); + System.out.println("Findings:"); + System.out.println(results); + return results; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END list_filtered_findings] + + /** + * List findings at a specific time under a source. + * + * @param sourceName The source to list findings at a specific time for. + */ + // [START list_findings_at_time] + static ImmutableList listFindingsAtTime(SourceName sourceName) { + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // SourceName sourceName = SourceName.of(/*organizationId=*/"123234324", + // /*sourceId=*/"423432321"); + + // 5 days ago + Instant fiveDaysAgo = Instant.now().minus(Duration.ofDays(5)); + + ListFindingsRequest.Builder request = + ListFindingsRequest.newBuilder() + .setParent(sourceName.toString()) + .setReadTime( + Timestamp.newBuilder() + .setSeconds(fiveDaysAgo.getEpochSecond()) + .setNanos(fiveDaysAgo.getNano())); + + // Call the API. + ListFindingsPagedResponse response = client.listFindings(request.build()); + + // This creates one list for all findings. If your organization has a large number of + // findings this can cause out of memory issues. You can process them in incrementally + // by returning the Iterable returned response.iterateAll() directly. + ImmutableList results = ImmutableList.copyOf(response.iterateAll()); + System.out.println("Findings:"); + System.out.println(results); + return results; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END list_findings_at_time] + + /** + * Demonstrate calling testIamPermissions to determin if the service account has the correct + * permissions. + * + * @param sourceName The source to create a finding for. + */ + // [START test_iam_permissions] + static TestIamPermissionsResponse testIamPermissions(SourceName sourceName) { + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // SourceName sourceName = SourceName.of(/*organizationId=*/"123234324", + // /*sourceId=*/"423432321"); + + // Iam permission to test. + List permissionsToTest = new ArrayList<>(); + permissionsToTest.add("securitycenter.findings.update"); + + // Call the API. + TestIamPermissionsResponse response = + client.testIamPermissions(sourceName.toString(), permissionsToTest); + System.out.println("IAM Permission:"); + System.out.println(response); + + return response; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END test_iam_permissions] + + /** + * Group all findings under an organization across all sources by their specified properties (e.g. + * category). + * + * @param organizationName The organizatoin to group all findings for. + */ + // [START group_all_findings] + static ImmutableList groupFindings(OrganizationName organizationName) { + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // OrganizationName organizationName = OrganizationName.of("123234324"); + SourceName sourceName = SourceName.of(organizationName.getOrganization(), "-"); + + GroupFindingsRequest.Builder request = + GroupFindingsRequest.newBuilder().setParent(sourceName.toString()).setGroupBy("category"); + + // Call the API. + GroupFindingsPagedResponse response = client.groupFindings(request.build()); + + // This creates one list for all findings. If your organization has a large number of + // findings + // this can cause out of memory issues. You can process them batches by returning + // the Iterable returned response.iterateAll() directly. + ImmutableList results = ImmutableList.copyOf(response.iterateAll()); + System.out.println("Findings:"); + System.out.println(results); + return results; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END group_all_findings] + + /** + * Group findings under an organization and a source by their specified properties (e.g. + * category). + * + * @param sourceName The source to limit the findings to. + */ + // [START group_findings_with_source] + static ImmutableList groupFindingsWithSource(SourceName sourceName) { + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // SourceName sourceName = SourceName.of(/*organization=*/"123234324",/*source=*/ + // "423432321"); + + GroupFindingsRequest.Builder request = + GroupFindingsRequest.newBuilder().setParent(sourceName.toString()).setGroupBy("category"); + + // Call the API. + GroupFindingsPagedResponse response = client.groupFindings(request.build()); + + // This creates one list for all findings. If your organization has a large number of + // findings + // this can cause out of memory issues. You can process them batches by returning + // the Iterable returned response.iterateAll() directly. + ImmutableList results = ImmutableList.copyOf(response.iterateAll()); + System.out.println("Findings:"); + System.out.println(results); + return results; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END group_findings_with_source] + + /** + * Group active findings under an organization and a source by their specified properties (e.g. + * category). + * + * @param sourceName The source to limit the findings to. + */ + // [START group_active_findings_with_source] + static ImmutableList groupActiveFindingsWithSource(SourceName sourceName) { + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // SourceName sourceName = SourceName.of(/*organization=*/"123234324",/*source=*/ + // "423432321"); + + GroupFindingsRequest.Builder request = + GroupFindingsRequest.newBuilder() + .setParent(sourceName.toString()) + .setGroupBy("category") + .setFilter("state=\"ACTIVE\""); + + // Call the API. + GroupFindingsPagedResponse response = client.groupFindings(request.build()); + + // This creates one list for all findings. If your organization has a large number of + // findings + // this can cause out of memory issues. You can process them batches by returning + // the Iterable returned response.iterateAll() directly. + ImmutableList results = ImmutableList.copyOf(response.iterateAll()); + System.out.println("Findings:"); + System.out.println(results); + return results; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END group_active_findings_with_source] + + /** + * Group active findings under an organization and a source by their specified properties (e.g. + * category) at a specified time. + * + * @param sourceName The source to limit the findings to. + */ + // [START group_active_findings_with_source_at_time] + static ImmutableList groupActiveFindingsWithSourceAtTime(SourceName sourceName) { + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // SourceName sourceName = SourceName.of(/*organization=*/"123234324",/*source=*/ + // "423432321"); + + // 1 day ago + Instant oneDayAgo = Instant.now().minusSeconds(60 * 60 * 24); + + GroupFindingsRequest.Builder request = + GroupFindingsRequest.newBuilder() + .setParent(sourceName.toString()) + .setGroupBy("category") + .setFilter("state=\"ACTIVE\"") + .setReadTime( + Timestamp.newBuilder() + .setSeconds(oneDayAgo.getEpochSecond()) + .setNanos(oneDayAgo.getNano())); + + // Call the API. + GroupFindingsPagedResponse response = client.groupFindings(request.build()); + + // This creates one list for all findings. If your organization has a large number of + // findings + // this can cause out of memory issues. You can process them batches by returning + // the Iterable returned response.iterateAll() directly. + ImmutableList results = ImmutableList.copyOf(response.iterateAll()); + System.out.println("Findings:"); + System.out.println(results); + return results; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END group_active_findings_with_source_at_time] + + /** + * Group active findings under an organization and a source by their state_changes + * (ADDED/CHANGED/UNCHANGED) during a period. + * + * @param sourceName The source to limit the findings to. + */ + // [START group_active_findings_with_source_and_compare_duration] + static ImmutableList groupActiveFindingsWithSourceAndCompareDuration( + SourceName sourceName, Duration duration) { + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // SourceName sourceName = SourceName.of(/*organization=*/"123234324",/*source=*/ + // "423432321"); + + GroupFindingsRequest.Builder request = + GroupFindingsRequest.newBuilder() + .setParent(sourceName.toString()) + .setGroupBy("state_change") + .setFilter("state=\"ACTIVE\""); + request + .getCompareDurationBuilder() + .setSeconds(duration.getSeconds()) + .setNanos(duration.getNano()); + + // Call the API. + GroupFindingsPagedResponse response = client.groupFindings(request.build()); + + // This creates one list for all findings. If your organization has a large number of + // findings + // this can cause out of memory issues. You can process them batches by returning + // the Iterable returned response.iterateAll() directly. + ImmutableList results = ImmutableList.copyOf(response.iterateAll()); + System.out.println("Findings:"); + System.out.println(results); + return results; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END group_active_findings_with_source_and_compare_duration] +} diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/securitycenter/snippets/OrganizationSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/securitycenter/snippets/OrganizationSnippets.java new file mode 100644 index 000000000000..712323cc1bae --- /dev/null +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/securitycenter/snippets/OrganizationSnippets.java @@ -0,0 +1,91 @@ +/* + * 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. + */ +package com.google.cloud.examples.securitycenter.snippets; + +import com.google.cloud.securitycenter.v1.GetOrganizationSettingsRequest; +import com.google.cloud.securitycenter.v1.OrganizationName; +import com.google.cloud.securitycenter.v1.OrganizationSettings; +import com.google.cloud.securitycenter.v1.SecurityCenterClient; +import com.google.cloud.securitycenter.v1.UpdateOrganizationSettingsRequest; +import com.google.protobuf.FieldMask; +import java.io.IOException; + +/** Snippets for how to work with Organizations in Cloud Security Command Center. */ +public class OrganizationSnippets { + + private OrganizationSnippets() {} + + /** + * Gets current settings for an organization. + * + * @param organizationName The organization to get settings for. + */ + // [START get_organization_settings] + static OrganizationSettings getOrganizationSettings(OrganizationName organizationName) { + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // Start setting up a request to get OrganizationSettings for. + // OrganizationName organizationName = OrganizationName.of(/*organizationId=*/"123234324"); + GetOrganizationSettingsRequest.Builder request = + GetOrganizationSettingsRequest.newBuilder() + .setName(organizationName.toString() + "/organizationSettings"); + + // Call the API. + OrganizationSettings response = client.getOrganizationSettings(request.build()); + + System.out.println("Organization Settings:"); + System.out.println(response); + return response; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END get_organization_settings] + + /** + * Update Asset Discovery OrganizationSettings for an organization + * + * @param organizationName The organization to update settings for. + */ + // [START update_organization_settings] + static OrganizationSettings updateOrganizationSettings(OrganizationName organizationName) { + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // Start setting up a request to update OrganizationSettings for. + // OrganizationName organizationName = OrganizationName.of(/*organizationId=*/"123234324"); + OrganizationSettings organizationSettings = + OrganizationSettings.newBuilder() + .setName(organizationName.toString() + "/organizationSettings") + .setEnableAssetDiscovery(true) + .build(); + FieldMask updateMask = FieldMask.newBuilder().addPaths("enable_asset_discovery").build(); + + UpdateOrganizationSettingsRequest.Builder request = + UpdateOrganizationSettingsRequest.newBuilder() + .setOrganizationSettings(organizationSettings) + .setUpdateMask(updateMask); + + // Call the API. + OrganizationSettings response = client.updateOrganizationSettings(request.build()); + + System.out.println("Organization Settings have been updated:"); + System.out.println(response); + return response; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END update_organization_settings] + +} diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/securitycenter/snippets/SecurityMarkSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/securitycenter/snippets/SecurityMarkSnippets.java new file mode 100644 index 000000000000..fe2babce754d --- /dev/null +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/securitycenter/snippets/SecurityMarkSnippets.java @@ -0,0 +1,256 @@ +/* + * 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. + */ +package com.google.cloud.examples.securitycenter.snippets; + +import com.google.cloud.securitycenter.v1.FindingName; +import com.google.cloud.securitycenter.v1.ListAssetsRequest; +import com.google.cloud.securitycenter.v1.ListAssetsResponse.ListAssetsResult; +import com.google.cloud.securitycenter.v1.ListFindingsRequest; +import com.google.cloud.securitycenter.v1.ListFindingsResponse.ListFindingsResult; +import com.google.cloud.securitycenter.v1.OrganizationName; +import com.google.cloud.securitycenter.v1.SecurityCenterClient; +import com.google.cloud.securitycenter.v1.SecurityCenterClient.ListAssetsPagedResponse; +import com.google.cloud.securitycenter.v1.SecurityCenterClient.ListFindingsPagedResponse; +import com.google.cloud.securitycenter.v1.SecurityMarks; +import com.google.cloud.securitycenter.v1.SourceName; +import com.google.cloud.securitycenter.v1.UpdateSecurityMarksRequest; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.google.protobuf.FieldMask; +import java.io.IOException; + +public class SecurityMarkSnippets { + + private SecurityMarkSnippets() {} + + /** + * Add security mark to an asset. + * + * @param assetName The asset resource to add the security mark for. + */ + // [START add_to_asset] + static SecurityMarks addToAsset(String assetName) { + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // String assetName = "organizations/123123342/assets/12312321"; + // Start setting up a request to add security marks for an asset. + ImmutableMap markMap = ImmutableMap.of("key_a", "value_a", "key_b", "value_b"); + + // Add security marks and field mask for security marks. + SecurityMarks securityMarks = + SecurityMarks.newBuilder() + .setName(assetName + "/securityMarks") + .putAllMarks(markMap) + .build(); + FieldMask updateMask = + FieldMask.newBuilder().addPaths("marks.key_a").addPaths("marks.key_b").build(); + + UpdateSecurityMarksRequest request = + UpdateSecurityMarksRequest.newBuilder() + .setSecurityMarks(securityMarks) + .setUpdateMask(updateMask) + .build(); + + // Call the API. + SecurityMarks response = client.updateSecurityMarks(request); + + System.out.println("Security Marks:"); + System.out.println(response); + return response; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END add_to_asset] + + /** + * Clear security marks for an asset. + * + * @param assetName The asset resource to clear the security marks for. + */ + // [START clear_from_asset] + static SecurityMarks clearFromAsset(String assetName) { + // String assetName = "organizations/123123342/assets/12312321"; + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // Start setting up a request to clear security marks for an asset. + // Create security mark and field mask for clearing security marks. + SecurityMarks securityMarks = + SecurityMarks.newBuilder().setName(assetName + "/securityMarks").build(); + FieldMask updateMask = + FieldMask.newBuilder().addPaths("marks.key_a").addPaths("marks.key_b").build(); + + UpdateSecurityMarksRequest request = + UpdateSecurityMarksRequest.newBuilder() + .setSecurityMarks(securityMarks) + .setUpdateMask(updateMask) + .build(); + + // Call the API. + SecurityMarks response = client.updateSecurityMarks(request); + + System.out.println("Security Marks cleared:"); + System.out.println(response); + return response; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END clear_from_asset] + + /** + * Deletes and updates a security mark for an asset. + * + * @param assetName The asset resource path to update and remove the security marks for. + */ + // [START delete_and_update_marks] + static SecurityMarks deleteAndUpdateMarks(String assetName) { + // String assetName = "organizations/123123342/assets/12312321"; + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // Start setting up a request to clear and update security marks for an asset. + // Create security mark and field mask for clearing security marks. + SecurityMarks securityMarks = + SecurityMarks.newBuilder() + .setName(assetName + "/securityMarks") + .putMarks("key_a", "new_value_for_a") + .build(); + FieldMask updateMask = + FieldMask.newBuilder().addPaths("marks.key_a").addPaths("marks.key_b").build(); + + UpdateSecurityMarksRequest request = + UpdateSecurityMarksRequest.newBuilder() + .setSecurityMarks(securityMarks) + .setUpdateMask(updateMask) + .build(); + + // Call the API. + SecurityMarks response = client.updateSecurityMarks(request); + + System.out.println("Security Marks updated and cleared:"); + System.out.println(response); + return response; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END delete_and_update_marks] + + /** + * Add security mark to a finding. + * + * @param findingName The finding resource path to add the security mark for. + */ + // [START add_to_finding] + static SecurityMarks addToFinding(FindingName findingName) { + // FindingName findingName = FindingName.of(/*organization=*/"123234324", + // /*source=*/"423432321", /*findingId=*/"samplefindingid2"); + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // Start setting up a request to add security marks for a finding. + ImmutableMap markMap = ImmutableMap.of("key_a", "value_a", "key_b", "value_b"); + + // Add security marks and field mask for security marks. + SecurityMarks securityMarks = + SecurityMarks.newBuilder() + .setName(findingName + "/securityMarks") + .putAllMarks(markMap) + .build(); + FieldMask updateMask = + FieldMask.newBuilder().addPaths("marks.key_a").addPaths("marks.key_b").build(); + + UpdateSecurityMarksRequest request = + UpdateSecurityMarksRequest.newBuilder() + .setSecurityMarks(securityMarks) + .setUpdateMask(updateMask) + .build(); + + // Call the API. + SecurityMarks response = client.updateSecurityMarks(request); + + System.out.println("Security Marks:"); + System.out.println(response); + return response; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END add_to_finding] + + /** + * Lists all assets with a filter on security marks. + * + * @param organizationName The organization to list assets for. + */ + // [START list_assets_with_filter] + static ImmutableList listAssetsWithQueryMarks( + OrganizationName organizationName) { + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // Start setting up a request for to list all assets filtered by a specific security mark. + // OrganizationName organizationName = OrganizationName.of(/*organizationId=*/"123234324"); + ListAssetsRequest request = + ListAssetsRequest.newBuilder() + .setParent(organizationName.toString()) + .setFilter("security_marks.marks.key_a = \"value_a\"") + .build(); + + // Call the API. + ListAssetsPagedResponse response = client.listAssets(request); + + // This creates one list for all assets. If your organization has a large number of assets + // this can cause out of memory issues. You can process them batches by returning + // the Iterable returned response.iterateAll() directly. + ImmutableList results = ImmutableList.copyOf(response.iterateAll()); + System.out.println("Assets with security mark - key_a=value_a:"); + System.out.println(results); + return results; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END list_assets_with_filter] + + /** + * List all findings with a filter on security marks. + * + * @param sourceName The source to list filtered findings for. + */ + // [START list_filtered_findings] + static ImmutableList listFindingsWithQueryMarks(SourceName sourceName) { + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // Start setting up a request for to list all findings filtered by a specific security mark. + // SourceName sourceName = SourceName.of(/*organization=*/"123234324",/*source=*/ + // "423432321"); + + String filter = "NOT security_marks.marks.key_a=\"value_a\""; + + ListFindingsRequest.Builder request = + ListFindingsRequest.newBuilder().setParent(sourceName.toString()).setFilter(filter); + + // Call the API. + ListFindingsPagedResponse response = client.listFindings(request.build()); + + // This creates one list for all findings in the filter.If your organization has a large + // number of + // findings this can cause out of memory issues. You can process them batches by returning + // the Iterable returned response.iterateAll() directly. + ImmutableList results = ImmutableList.copyOf(response.iterateAll()); + System.out.println("Findings with security mark - key_a=value_a:"); + System.out.println(results); + return results; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END list_filtered_findings] + +} diff --git a/google-cloud-examples/src/main/java/com/google/cloud/examples/securitycenter/snippets/SourceSnippets.java b/google-cloud-examples/src/main/java/com/google/cloud/examples/securitycenter/snippets/SourceSnippets.java new file mode 100644 index 000000000000..0f6c84290aa2 --- /dev/null +++ b/google-cloud-examples/src/main/java/com/google/cloud/examples/securitycenter/snippets/SourceSnippets.java @@ -0,0 +1,215 @@ +/* + * 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. + */ +package com.google.cloud.examples.securitycenter.snippets; + +import com.google.cloud.securitycenter.v1.CreateSourceRequest; +import com.google.cloud.securitycenter.v1.GetSourceRequest; +import com.google.cloud.securitycenter.v1.ListSourcesRequest; +import com.google.cloud.securitycenter.v1.OrganizationName; +import com.google.cloud.securitycenter.v1.SecurityCenterClient; +import com.google.cloud.securitycenter.v1.SecurityCenterClient.ListSourcesPagedResponse; +import com.google.cloud.securitycenter.v1.Source; +import com.google.cloud.securitycenter.v1.SourceName; +import com.google.cloud.securitycenter.v1.UpdateSourceRequest; +import com.google.common.collect.ImmutableList; +import com.google.iam.v1.Binding; +import com.google.iam.v1.GetIamPolicyRequest; +import com.google.iam.v1.Policy; +import com.google.iam.v1.SetIamPolicyRequest; +import com.google.protobuf.FieldMask; +import java.io.IOException; + +/** Snippets for how to work with Sources in Cloud Security Command Center. */ +public class SourceSnippets { + private SourceSnippets() {} + + /** + * Create a source under an organization. + * + * @param organizationName The organization for the source. + */ + // [START create_source] + static Source createSource(OrganizationName organizationName) { + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // Start setting up a request to create a source in an organization. + // OrganizationName organizationName = OrganizationName.of(/*organizationId=*/"123234324"); + Source source = + Source.newBuilder() + .setDisplayName("Customized Display Name") + .setDescription("A new custom source that does X") + .build(); + + CreateSourceRequest.Builder request = + CreateSourceRequest.newBuilder().setParent(organizationName.toString()).setSource(source); + + // Call the API. + Source response = client.createSource(request.build()); + + System.out.println("Created Source: " + response); + return response; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END create_source] + + /** + * List sources under an organization. + * + * @param organizationName The organization for the source. + */ + // [START list_source] + static ImmutableList listSources(OrganizationName organizationName) { + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // Start setting up a request to list sources in an organization. + // OrganizationName organizationName = OrganizationName.of(/*organizationId=*/"123234324"); + ListSourcesRequest.Builder request = + ListSourcesRequest.newBuilder().setParent(organizationName.toString()); + + // Call the API. + ListSourcesPagedResponse response = client.listSources(request.build()); + + // This creates one list for all sources. If your organization has a large number of sources + // this can cause out of memory issues. You can process them batches by returning + // the Iterable returned response.iterateAll() directly. + ImmutableList results = ImmutableList.copyOf(response.iterateAll()); + System.out.println("Sources:"); + System.out.println(results); + return results; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END list_source] + + /** + * Update a source under an organization. + * + * @param sourceName The source to update. + */ + // [START update_source] + static Source updateSource(SourceName sourceName) { + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // Start setting up a request to update a source. + // SourceName sourceName = SourceName.of(/*organization=*/"123234324",/*source=*/ + // "423432321"); + Source source = + Source.newBuilder() + .setDisplayName("Updated Display Name") + .setName(sourceName.toString()) + .build(); + FieldMask updateMask = FieldMask.newBuilder().addPaths("display_name").build(); + + UpdateSourceRequest.Builder request = + UpdateSourceRequest.newBuilder().setSource(source).setUpdateMask(updateMask); + + // Call the API. + Source response = client.updateSource(request.build()); + + System.out.println("Updated Source: " + response); + return response; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END update_source] + + /** + * Get a source under an organization. + * + * @param sourceName The source to get. + */ + // [START get_source] + static Source getSource(SourceName sourceName) { + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // Start setting up a request to get a source. + // SourceName sourceName = SourceName.of(/*organization=*/"123234324",/*source=*/ + // "423432321"); + GetSourceRequest.Builder request = + GetSourceRequest.newBuilder().setName(sourceName.toString()); + + // Call the API. + Source response = client.getSource(request.build()); + + System.out.println("Source: " + response); + return response; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END get_source] + + /** + * Set IAM policy for a source. + * + * @param sourceName The source to set IAM Policy for. + */ + // [START set_source_iam_policy] + static Policy setIamPolicySource(SourceName sourceName, String userEmail) { + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // userEmail = "someuser@domain.com" + // Set up IAM Policy for the user userMail to use the role findingsEditor. + // The user must be a valid google account. + Policy oldPolicy = client.getIamPolicy(sourceName.toString()); + Binding bindings = + Binding.newBuilder() + .setRole("roles/securitycenter.findingsEditor") + .addMembers("user:" + userEmail) + .build(); + Policy policy = oldPolicy.toBuilder().addBindings(bindings).build(); + + // Start setting up a request to set IAM policy for a source. + // SourceName sourceName = SourceName.of("123234324", "423432321"); + SetIamPolicyRequest.Builder request = + SetIamPolicyRequest.newBuilder().setPolicy(policy).setResource(sourceName.toString()); + + // Call the API. + Policy response = client.setIamPolicy(request.build()); + + System.out.println("Policy: " + response); + return response; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END set_source_iam_policy] + + /** + * Get IAM policy for a source. + * + * @param sourceName The source to set IAM Policy for. + */ + // [START get_source_iam_policy] + static Policy getIamPolicySource(SourceName sourceName) { + try (SecurityCenterClient client = SecurityCenterClient.create()) { + // Start setting up a request to get IAM policy for a source. + // SourceName sourceName = SourceName.of(/*organization=*/"123234324",/*source=*/ + // "423432321"); + GetIamPolicyRequest request = + GetIamPolicyRequest.newBuilder().setResource(sourceName.toString()).build(); + + // Call the API. + Policy response = client.getIamPolicy(request); + + System.out.println("Policy: " + response); + return response; + } catch (IOException e) { + throw new RuntimeException("Couldn't create client.", e); + } + } + // [END get_source_iam_policy] + +} diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/securitycenter/snippets/ITAssetSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/securitycenter/snippets/ITAssetSnippets.java index b3198b52075f..04261bd25a6e 100644 --- a/google-cloud-examples/src/test/java/com/google/cloud/examples/securitycenter/snippets/ITAssetSnippets.java +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/securitycenter/snippets/ITAssetSnippets.java @@ -19,11 +19,14 @@ import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.assertEquals; -import com.google.cloud.securitycenter.v1beta1.ListAssetsResponse.ListAssetsResult; -import com.google.cloud.securitycenter.v1beta1.ListAssetsResponse.ListAssetsResult.State; -import com.google.cloud.securitycenter.v1beta1.OrganizationName; +import com.google.cloud.securitycenter.v1.GroupResult; +import com.google.cloud.securitycenter.v1.ListAssetsResponse.ListAssetsResult; +import com.google.cloud.securitycenter.v1.ListAssetsResponse.ListAssetsResult.StateChange; +import com.google.cloud.securitycenter.v1.OrganizationName; import com.google.common.collect.ImmutableList; +import java.io.ByteArrayOutputStream; import java.io.IOException; +import java.io.PrintStream; import org.junit.Test; import org.threeten.bp.Duration; import org.threeten.bp.Instant; @@ -51,7 +54,7 @@ public void testBeforeDateNoAssetsReturned() { @Test public void testListAssetsNoFilterOrDate() { - assertTrue(59 >= AssetSnippets.listAssets(getOrganizationId()).size()); + assertTrue(59 <= AssetSnippets.listAssets(getOrganizationId()).size()); } @Test @@ -67,7 +70,47 @@ public void testChangesReturnsValues() { getOrganizationId(), Duration.ofDays(3), SOMETHING_INSTANCE); assertTrue("Result: " + result.toString(), result.toString().contains("ADDED")); assertTrue(3 >= result.size()); - assertEquals(result.get(0).getState(), State.ADDED); + assertEquals(result.get(0).getStateChange(), StateChange.ADDED); + } + + @Test + public void testGroupAssets() { + ImmutableList results = AssetSnippets.groupAssets(getOrganizationId()); + assertTrue(results.size() > 0); + } + + @Test + public void testGroupAssetsWithFilter() { + ImmutableList results = AssetSnippets.groupAssetsWithFilter(getOrganizationId()); + assertTrue(results.size() > 0); + } + + @Test + public void testGroupAssetsWithCompareDuration() { + ImmutableList results = + AssetSnippets.groupAssetsWithCompareDuration( + getOrganizationId(), Duration.ofSeconds(86400)); + assertTrue(results.size() > 0); + } + + @Test + public void testRunAssetDiscovery() throws IOException { + PrintStream oldStream = System.out; + try { + + ByteArrayOutputStream capture = new ByteArrayOutputStream(); + PrintStream out = new PrintStream(capture); + System.setOut(out); + AssetSnippets.runAssetDiscovery(getOrganizationId()); + + out.flush(); + assertTrue( + capture.toString(), + capture.toString().equals("Asset discovery runs asynchronously.\n") + || capture.toString().equals("Asset discovery run already in progress.\n")); + } finally { + System.setOut(oldStream); + } } private static OrganizationName getOrganizationId() { diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/securitycenter/snippets/ITFindingSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/securitycenter/snippets/ITFindingSnippets.java new file mode 100644 index 000000000000..5634a03e84e7 --- /dev/null +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/securitycenter/snippets/ITFindingSnippets.java @@ -0,0 +1,126 @@ +/* + * 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. + */ +package com.google.cloud.examples.securitycenter.snippets; + +import static junit.framework.TestCase.assertEquals; +import static junit.framework.TestCase.assertNotNull; +import static junit.framework.TestCase.assertTrue; + +import com.google.cloud.securitycenter.v1.Finding.State; +import com.google.cloud.securitycenter.v1.FindingName; +import com.google.cloud.securitycenter.v1.OrganizationName; +import com.google.cloud.securitycenter.v1.SourceName; +import com.google.protobuf.Value; +import java.io.IOException; +import org.junit.BeforeClass; +import org.junit.Test; +import org.threeten.bp.Duration; + +/** Smoke tests for {@link com.google.cloud.examples.securitycenter.snippets.FindingSnippets} */ +public class ITFindingSnippets { + + private static SourceName SOURCE_NAME; + private static FindingName FINDING_NAME; + + @BeforeClass + public static void setUp() throws IOException { + SOURCE_NAME = SourceName.parse(SourceSnippets.createSource(getOrganizationId()).getName()); + FINDING_NAME = + FindingName.parse(FindingSnippets.createFinding(SOURCE_NAME, "testfindingid").getName()); + } + + @Test + public void testCreateFinding() throws IOException { + assertNotNull(FindingSnippets.createFinding(SOURCE_NAME, "samplefindingid")); + } + + @Test + public void testCreateFindingWithSourceProperties() throws IOException { + assertNotNull(FindingSnippets.createFindingWithSourceProperties(SOURCE_NAME)); + } + + @Test + public void testUpdateFinding() throws IOException { + Value stringValue = Value.newBuilder().setStringValue("value").build(); + assertTrue( + FindingSnippets.updateFinding(FINDING_NAME) + .getSourcePropertiesMap() + .get("stringKey") + .equals(stringValue)); + } + + @Test + public void testUpdateFindingState() throws IOException { + Value stringValue = Value.newBuilder().setStringValue("value").build(); + assertTrue(FindingSnippets.setFindingState(FINDING_NAME).getState().equals(State.INACTIVE)); + } + + @Test + public void testListAllFindings() throws IOException { + assertTrue(FindingSnippets.listAllFindings(getOrganizationId()).size() > 1); + } + + @Test + public void testListFilteredFindings() throws IOException { + assertTrue(FindingSnippets.listFilteredFindings(SOURCE_NAME).size() > 0); + } + + @Test + public void testListFindingsAtTime() throws IOException { + assertTrue(FindingSnippets.listFindingsAtTime(SOURCE_NAME).size() == 0); + } + + @Test + public void testTestIamPermissions() throws IOException { + assertTrue( + FindingSnippets.testIamPermissions(SOURCE_NAME) + .getPermissions(0) + .equals("securitycenter.findings.update")); + } + + @Test + public void testGroupFindings() throws IOException { + assertTrue(FindingSnippets.groupFindings(getOrganizationId()).size() > 0); + } + + @Test + public void testGroupFindingsWithSource() throws IOException { + assertTrue(FindingSnippets.groupFindingsWithSource(SOURCE_NAME).size() > 0); + } + + @Test + public void testGroupActiveFindingsWithSource() throws IOException { + assertTrue(FindingSnippets.groupActiveFindingsWithSource(SOURCE_NAME).size() > 0); + } + + @Test + public void testGroupActiveFindingsWithSourceAtTime() throws IOException { + assertEquals(0, FindingSnippets.groupActiveFindingsWithSourceAtTime(SOURCE_NAME).size()); + } + + @Test + public void testGroupActiveFindingsWithSourceAndCompareDuration() throws IOException { + assertTrue( + FindingSnippets.groupActiveFindingsWithSourceAndCompareDuration( + SOURCE_NAME, Duration.ofDays(1)) + .size() + > 0); + } + + private static OrganizationName getOrganizationId() { + return OrganizationName.of(System.getenv("GCLOUD_ORGANIZATION")); + } +} diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/securitycenter/snippets/ITOrganizationSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/securitycenter/snippets/ITOrganizationSnippets.java new file mode 100644 index 000000000000..699299d6eaaa --- /dev/null +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/securitycenter/snippets/ITOrganizationSnippets.java @@ -0,0 +1,43 @@ +/* + * 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. + */ +package com.google.cloud.examples.securitycenter.snippets; + +import static junit.framework.TestCase.assertNotNull; +import static junit.framework.TestCase.assertTrue; + +import com.google.cloud.securitycenter.v1.OrganizationName; +import java.io.IOException; +import org.junit.Test; + +public class ITOrganizationSnippets { + + @Test + public void testGetOrganizationSettings() throws IOException { + assertNotNull(OrganizationSnippets.getOrganizationSettings(getOrganizationId())); + } + + @Test + public void testUpdateOrganizationSettings() throws IOException { + assertTrue( + OrganizationSnippets.updateOrganizationSettings(getOrganizationId()) + .getAssetDiscoveryConfig() + .isInitialized()); + } + + private static OrganizationName getOrganizationId() { + return OrganizationName.of(System.getenv("GCLOUD_ORGANIZATION")); + } +} diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/securitycenter/snippets/ITSecurityMarkSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/securitycenter/snippets/ITSecurityMarkSnippets.java new file mode 100644 index 000000000000..a3c07c118e8d --- /dev/null +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/securitycenter/snippets/ITSecurityMarkSnippets.java @@ -0,0 +1,85 @@ +/* + * 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. + */ +package com.google.cloud.examples.securitycenter.snippets; + +import static junit.framework.TestCase.assertFalse; +import static junit.framework.TestCase.assertTrue; + +import com.google.cloud.securitycenter.v1.Asset; +import com.google.cloud.securitycenter.v1.Finding; +import com.google.cloud.securitycenter.v1.FindingName; +import com.google.cloud.securitycenter.v1.OrganizationName; +import com.google.cloud.securitycenter.v1.SourceName; +import java.io.IOException; +import org.junit.BeforeClass; +import org.junit.Test; + +public class ITSecurityMarkSnippets { + + private static Asset ASSET; + private static SourceName SOURCE_NAME; + private static Finding FINDING; + + @BeforeClass + public static void setUp() throws IOException { + ASSET = AssetSnippets.listAssets(getOrganizationId()).get(0).getAsset(); + SOURCE_NAME = SourceName.parse(SourceSnippets.createSource(getOrganizationId()).getName()); + FINDING = FindingSnippets.createFinding(SOURCE_NAME, "testfindingid"); + } + + @Test + public void testAddToAsset() throws IOException { + assertTrue( + SecurityMarkSnippets.addToAsset(ASSET.getName()) + .getMarksOrThrow("key_a") + .equals("value_a")); + } + + @Test + public void testClearFromAsset() throws IOException { + assertFalse(SecurityMarkSnippets.clearFromAsset(ASSET.getName()).containsMarks("key_a")); + } + + @Test + public void testDeleteAndUpdateMarks() throws IOException { + assertTrue( + SecurityMarkSnippets.deleteAndUpdateMarks(ASSET.getName()) + .getMarksOrThrow("key_a") + .equals("new_value_for_a")); + } + + @Test + public void testAddToFinding() throws IOException { + assertTrue( + SecurityMarkSnippets.addToFinding(FindingName.parse(FINDING.getName())) + .getMarksOrThrow("key_a") + .equals("value_a")); + } + + @Test + public void testListAssetsWithQueryMarks() throws IOException { + assertTrue(SecurityMarkSnippets.listAssetsWithQueryMarks(getOrganizationId()).size() > 0); + } + + @Test + public void testListFindingsWithQueryMarks() throws IOException { + assertTrue(SecurityMarkSnippets.listFindingsWithQueryMarks(SOURCE_NAME).size() > 0); + } + + private static OrganizationName getOrganizationId() { + return OrganizationName.of(System.getenv("GCLOUD_ORGANIZATION")); + } +} diff --git a/google-cloud-examples/src/test/java/com/google/cloud/examples/securitycenter/snippets/ITSourceSnippets.java b/google-cloud-examples/src/test/java/com/google/cloud/examples/securitycenter/snippets/ITSourceSnippets.java new file mode 100644 index 000000000000..96d03a92483e --- /dev/null +++ b/google-cloud-examples/src/test/java/com/google/cloud/examples/securitycenter/snippets/ITSourceSnippets.java @@ -0,0 +1,75 @@ +/* + * 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. + */ +package com.google.cloud.examples.securitycenter.snippets; + +import static junit.framework.TestCase.assertNotNull; +import static junit.framework.TestCase.assertTrue; + +import com.google.cloud.securitycenter.v1.OrganizationName; +import com.google.cloud.securitycenter.v1.SourceName; +import java.io.IOException; +import org.junit.BeforeClass; +import org.junit.Test; + +/** Smoke tests for {@link com.google.cloud.examples.securitycenter.snippets.SourceSnippets} */ +public class ITSourceSnippets { + + private static SourceName SOURCE_NAME; + + @BeforeClass + public static void setUp() throws IOException { + SOURCE_NAME = SourceName.parse(SourceSnippets.createSource(getOrganizationId()).getName()); + } + + @Test + public void testCreateSource() throws IOException { + assertNotNull(SourceSnippets.createSource(getOrganizationId())); + } + + @Test + public void testListSources() throws IOException { + assertTrue(SourceSnippets.listSources(getOrganizationId()).size() > 1); + } + + @Test + public void testUpdateSource() throws IOException { + assertTrue( + SourceSnippets.updateSource(SOURCE_NAME).getDisplayName().equals("Updated Display Name")); + } + + @Test + public void testGetSource() throws IOException { + assertTrue(SourceSnippets.getSource(SOURCE_NAME).getName().equals(SOURCE_NAME.toString())); + } + + @Test + public void testSetSourceIamPolicy() throws IOException { + assertTrue( + SourceSnippets.setIamPolicySource(SOURCE_NAME, "csccclienttest@gmail.com") + .getBindings(0) + .getRole() + .equals("roles/securitycenter.findingsEditor")); + } + + @Test + public void testGetSourceIamPolicy() throws IOException { + assertNotNull(SourceSnippets.getIamPolicySource(SOURCE_NAME)); + } + + private static OrganizationName getOrganizationId() { + return OrganizationName.of(System.getenv("GCLOUD_ORGANIZATION")); + } +}