-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Add Snippets for working with Assets in Cloud Security Command Center. #4690
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
0de725a
Add Snippets for working with Assets in Cloud Security Command Center.
d1d7faa
Address code review comments.
870f100
remove securitycenter-it.cfg
1f2106c
update comments
c88e4cd
fix string remove firewall reference
70eed96
Fix format
4cac433
fix format
d100761
Address comments and fix bad docs/alignment with python example
dc01b85
Fix print description
emkornfield 6703809
Updates per rubrics
ca3af5c
fix warnings
4096ed2
Add Apache Headers
4bd510c
remove unused comment
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
193 changes: 193 additions & 0 deletions
193
...amples/src/main/java/com/google/cloud/examples/securitycenter/snippets/AssetSnippets.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,193 @@ | ||
| /* | ||
| * 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 | ||
| * | ||
| * 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. | ||
| */ | ||
| 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.common.base.MoreObjects; | ||
| import com.google.common.base.Preconditions; | ||
| import com.google.common.collect.ImmutableList; | ||
| import java.io.IOException; | ||
| import org.threeten.bp.Duration; | ||
| import org.threeten.bp.Instant; | ||
|
|
||
| /** Snippets for how to work with Assets in Cloud Security Command Center. */ | ||
| public class AssetSnippets { | ||
| private AssetSnippets() {} | ||
|
|
||
| /** | ||
| * Lists all assets for an organization. | ||
| * | ||
| * @param organizationName The organization to list assets for. | ||
| */ | ||
| // [START list_all_assets] | ||
| static ImmutableList<ListAssetsResult> 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"); | ||
| ListAssetsRequest.Builder request = | ||
| ListAssetsRequest.newBuilder().setParent(organizationName.toString()); | ||
|
|
||
| // Call the API. | ||
| 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 | ||
| // the Iterable returned response.iterateAll() directly. | ||
| ImmutableList<ListAssetsResult> 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 list_all_assets] | ||
|
|
||
| /** | ||
| * Lists all project assets for an organization. | ||
| * | ||
| * @param organizationName The organization to list assets for. | ||
| */ | ||
| // [START list_assets_with_filter] | ||
| static ImmutableList<ListAssetsResult> 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 = | ||
| ListAssetsRequest.newBuilder() | ||
| .setParent(organizationName.toString()) | ||
| .setFilter( | ||
| "security_center_properties.resource_type=\"google.cloud.resourcemanager.Project\"") | ||
| .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<ListAssetsResult> results = ImmutableList.copyOf(response.iterateAll()); | ||
| System.out.println("Projects:"); | ||
| System.out.println(results); | ||
| return results; | ||
| } catch (IOException e) { | ||
| throw new RuntimeException("Couldn't create client.", e); | ||
| } | ||
| } | ||
| // [END list_assets_with_filter] | ||
|
|
||
| /** | ||
| * Lists all project assets for an organization at a given point in time. | ||
| * | ||
| * @param organizationName The organization to list assets for. | ||
| * @param asOf The snapshot time to query for assets. If null defaults to one day ago. | ||
| */ | ||
| // [START list_assets_as_of_time] | ||
| static ImmutableList<ListAssetsResult> 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"); | ||
|
|
||
| // Initialize the builder with the organization and filter | ||
| ListAssetsRequest.Builder request = | ||
| ListAssetsRequest.newBuilder() | ||
| .setParent(organizationName.toString()) | ||
| .setFilter( | ||
| "security_center_properties.resource_type=\"google.cloud.resourcemanager.Project\""); | ||
|
|
||
| // Set read time to either the instant passed in or one day ago. | ||
| asOf = MoreObjects.firstNonNull(asOf, Instant.now().minus(Duration.ofDays(1))); | ||
| request.getReadTimeBuilder().setSeconds(asOf.getEpochSecond()).setNanos(asOf.getNano()); | ||
|
|
||
| // Call the API. | ||
| 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 | ||
| // the Iterable returned response.iterateAll() directly. | ||
| ImmutableList<ListAssetsResult> results = ImmutableList.copyOf(response.iterateAll()); | ||
| System.out.println("Projects:"); | ||
| System.out.println(results); | ||
| return results; | ||
| } catch (IOException e) { | ||
| throw new RuntimeException("Couldn't create client.", e); | ||
| } | ||
| } | ||
| // [END list_assets_as_of_time] | ||
|
|
||
| /** | ||
| * Returns Assets and metadata about assets activity (e.g. added, removed, no change) between | ||
| * between <code>asOf.minus(timespan)</code> and <code>asOf</code>. | ||
| * | ||
| * @param timeSpan The time-range to compare assets over. | ||
| * @param asOf The instant in time to query for. If null, current time is assumed. | ||
| */ | ||
| // [START list_asset_changes_status_changes] | ||
| static ImmutableList<ListAssetsResult> listAssetAndStatusChanges( | ||
| OrganizationName organizationName, Duration timeSpan, 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"); | ||
| ListAssetsRequest.Builder request = | ||
| ListAssetsRequest.newBuilder() | ||
| .setParent(organizationName.toString()) | ||
| .setFilter( | ||
| "security_center_properties.resource_type=\"google.cloud.resourcemanager.Project\""); | ||
| request | ||
| .getCompareDurationBuilder() | ||
| .setSeconds(timeSpan.getSeconds()) | ||
| .setNanos(timeSpan.getNano()); | ||
|
|
||
| // Set read time to either the instant passed in or now. | ||
| asOf = MoreObjects.firstNonNull(asOf, Instant.now()); | ||
| request.getReadTimeBuilder().setSeconds(asOf.getEpochSecond()).setNanos(asOf.getNano()); | ||
|
|
||
| // Call the API. | ||
| 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 | ||
| // the Iterable returned response.iterateAll() directly. | ||
| ImmutableList<ListAssetsResult> results = ImmutableList.copyOf(response.iterateAll()); | ||
| System.out.println("Projects:"); | ||
| System.out.println(results); | ||
| return results; | ||
| } catch (IOException e) { | ||
| throw new RuntimeException("Couldn't create client.", e); | ||
| } | ||
| } | ||
| // [END list_asset_changes_status_changes] | ||
|
|
||
| public static void main(String... args) { | ||
| String org_id = System.getenv("ORGANIZATION_ID"); | ||
| if (args.length > 0) { | ||
| org_id = args[0]; | ||
| } | ||
|
|
||
| Preconditions.checkNotNull( | ||
| org_id, | ||
| "Organization ID must either be set in the environment variable \"ORGANIZATION_ID\" or passed" | ||
| + " as the first parameter to the program."); | ||
|
|
||
| listAssetsWithFilter(OrganizationName.of(org_id)); | ||
| } | ||
| } | ||
76 changes: 76 additions & 0 deletions
76
...ples/src/test/java/com/google/cloud/examples/securitycenter/snippets/ITAssetSnippets.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,76 @@ | ||
| /* | ||
| * 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 | ||
| * | ||
| * 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. | ||
| */ | ||
|
|
||
| package com.google.cloud.examples.securitycenter.snippets; | ||
emkornfield marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| 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.common.collect.ImmutableList; | ||
| import java.io.IOException; | ||
| import org.junit.Test; | ||
| import org.threeten.bp.Duration; | ||
| import org.threeten.bp.Instant; | ||
| import org.threeten.bp.LocalDateTime; | ||
| import org.threeten.bp.ZoneOffset; | ||
|
|
||
| /** Smoke tests for {@link com.google.cloud.examples.securitycenter.snippets.AssetSnippets} */ | ||
| public class ITAssetSnippets { | ||
|
|
||
| private static final Instant NOTHING_INSTANCE = | ||
| LocalDateTime.of(2019, 1, 1, 0, 0).toInstant(ZoneOffset.UTC); | ||
| private static final Instant SOMETHING_INSTANCE = | ||
| LocalDateTime.of(2019, 3, 14, 8, 0).toInstant(ZoneOffset.ofHours((-8))); | ||
|
|
||
| @Test | ||
| public void mainRuns() throws IOException { | ||
| AssetSnippets.main(getOrganizationId().getOrganization()); | ||
| } | ||
|
|
||
| @Test | ||
| public void testBeforeDateNoAssetsReturned() { | ||
| assertTrue( | ||
| AssetSnippets.listAssetsAsOfYesterday(getOrganizationId(), NOTHING_INSTANCE).isEmpty()); | ||
| } | ||
|
|
||
| @Test | ||
| public void testListAssetsNoFilterOrDate() { | ||
| assertTrue(59 >= AssetSnippets.listAssets(getOrganizationId()).size()); | ||
| } | ||
|
|
||
| @Test | ||
| public void testListAssetsWithFilterAndInstance() { | ||
| assertTrue( | ||
| 3 >= AssetSnippets.listAssetsAsOfYesterday(getOrganizationId(), SOMETHING_INSTANCE).size()); | ||
| } | ||
|
|
||
| @Test | ||
| public void testChangesReturnsValues() { | ||
| ImmutableList<ListAssetsResult> result = | ||
| AssetSnippets.listAssetAndStatusChanges( | ||
| 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); | ||
| } | ||
|
|
||
| private static OrganizationName getOrganizationId() { | ||
| return OrganizationName.of(System.getenv("GCLOUD_ORGANIZATION")); | ||
| } | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.