Skip to content

Commit a0be08f

Browse files
melaniedejongkurtisvg
authored andcommitted
IAM: Add access code snippets and tests (#1597)
1 parent 501af84 commit a0be08f

File tree

9 files changed

+493
-2
lines changed

9 files changed

+493
-2
lines changed

iam/api-client/pom.xml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,11 @@
4141
<artifactId>google-api-services-iam</artifactId>
4242
<version>v1-rev20190704-1.30.1</version>
4343
</dependency>
44+
<dependency>
45+
<groupId>com.google.apis</groupId>
46+
<artifactId>google-api-services-cloudresourcemanager</artifactId>
47+
<version>v1-rev550-1.25.0</version>
48+
</dependency>
4449
<dependency>
4550
<groupId>commons-cli</groupId>
4651
<artifactId>commons-cli</artifactId>
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/* Copyright 2019 Google LLC
2+
*
3+
* Licensed under the Apache License, Version 2.0 (the "License");
4+
* you may not use this file except in compliance with the License.
5+
* You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software
10+
* distributed under the License is distributed on an "AS IS" BASIS,
11+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
* See the License for the specific language governing permissions and
13+
* limitations under the License.
14+
*/
15+
16+
package com.google.iam.snippets;
17+
18+
// [START iam_modify_policy_add_binding]
19+
import com.google.api.services.cloudresourcemanager.model.Binding;
20+
import com.google.api.services.cloudresourcemanager.model.Policy;
21+
import java.util.ArrayList;
22+
import java.util.List;
23+
24+
public class AddBinding {
25+
26+
// Adds a member to a role with no previous members.
27+
public static void addBinding(Policy policy) {
28+
// policy = service.Projects.GetIAmPolicy(new GetIamPolicyRequest(), your-project-id).Execute();
29+
30+
String role = "roles/role-to-add";
31+
List<String> members = new ArrayList<String>();
32+
members.add("user:[email protected]");
33+
34+
Binding binding = new Binding();
35+
binding.setRole(role);
36+
binding.setMembers(members);
37+
38+
policy.getBindings().add(binding);
39+
System.out.println("Added binding: " + binding.toString());
40+
}
41+
}
42+
// [END iam_modify_policy_add_binding]
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/* Copyright 2019 Google LLC
2+
*
3+
* Licensed under the Apache License, Version 2.0 (the "License");
4+
* you may not use this file except in compliance with the License.
5+
* You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software
10+
* distributed under the License is distributed on an "AS IS" BASIS,
11+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
* See the License for the specific language governing permissions and
13+
* limitations under the License.
14+
*/
15+
16+
package com.google.iam.snippets;
17+
18+
// [START iam_modify_policy_add_member]
19+
import com.google.api.services.cloudresourcemanager.model.Binding;
20+
import com.google.api.services.cloudresourcemanager.model.Policy;
21+
import java.util.List;
22+
23+
public class AddMember {
24+
25+
// Adds a member to a preexisting role.
26+
public static void addMember(Policy policy) {
27+
// policy = service.Projects.GetIAmPolicy(new GetIamPolicyRequest(), your-project-id).Execute();
28+
29+
String role = "roles/existing-role";
30+
String member = "user:[email protected]";
31+
32+
List<Binding> bindings = policy.getBindings();
33+
34+
for (Binding b : bindings) {
35+
if (b.getRole() == role) {
36+
b.getMembers().add(member);
37+
System.out.println("Member " + member + " added to role " + role);
38+
return;
39+
}
40+
}
41+
42+
System.out.println("Role not found in policy; member not added");
43+
}
44+
}
45+
// [END iam_modify_policy_add_member]
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/* Copyright 2019 Google LLC
2+
*
3+
* Licensed under the Apache License, Version 2.0 (the "License");
4+
* you may not use this file except in compliance with the License.
5+
* You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software
10+
* distributed under the License is distributed on an "AS IS" BASIS,
11+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
* See the License for the specific language governing permissions and
13+
* limitations under the License.
14+
*/
15+
16+
package com.google.iam.snippets;
17+
18+
// [START iam_get_policy]
19+
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
20+
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
21+
import com.google.api.client.json.jackson2.JacksonFactory;
22+
import com.google.api.services.cloudresourcemanager.CloudResourceManager;
23+
import com.google.api.services.cloudresourcemanager.model.GetIamPolicyRequest;
24+
import com.google.api.services.cloudresourcemanager.model.Policy;
25+
import com.google.api.services.iam.v1.IamScopes;
26+
import java.io.IOException;
27+
import java.security.GeneralSecurityException;
28+
import java.util.Collections;
29+
30+
public class GetPolicy {
31+
32+
// Gets a project's policy.
33+
public static Policy getPolicy(String projectId) {
34+
// projectId = "my-project-id"
35+
36+
Policy policy = null;
37+
38+
CloudResourceManager service = null;
39+
try {
40+
service = createCloudResourceManagerService();
41+
} catch (IOException | GeneralSecurityException e) {
42+
System.out.println("Unable to initialize service: \n" + e.toString());
43+
return policy;
44+
}
45+
46+
try {
47+
GetIamPolicyRequest request = new GetIamPolicyRequest();
48+
policy = service.projects().getIamPolicy(projectId, request).execute();
49+
System.out.println("Policy retrieved: " + policy.toString());
50+
return policy;
51+
} catch (IOException e) {
52+
System.out.println("Unable to get policy: \n" + e.toString());
53+
return policy;
54+
}
55+
}
56+
57+
public static CloudResourceManager createCloudResourceManagerService()
58+
throws IOException, GeneralSecurityException {
59+
// Use the Application Default Credentials strategy for authentication. For more info, see:
60+
// https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
61+
GoogleCredential credential =
62+
GoogleCredential.getApplicationDefault()
63+
.createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
64+
65+
CloudResourceManager service =
66+
new CloudResourceManager.Builder(
67+
GoogleNetHttpTransport.newTrustedTransport(),
68+
JacksonFactory.getDefaultInstance(),
69+
credential)
70+
.setApplicationName("service-accounts")
71+
.build();
72+
return service;
73+
}
74+
}
75+
// [END iam_get_policy]
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/* Copyright 2019 Google LLC
2+
*
3+
* Licensed under the Apache License, Version 2.0 (the "License");
4+
* you may not use this file except in compliance with the License.
5+
* You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software
10+
* distributed under the License is distributed on an "AS IS" BASIS,
11+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
* See the License for the specific language governing permissions and
13+
* limitations under the License.
14+
*/
15+
16+
package com.google.iam.snippets;
17+
18+
// [START iam_modify_policy_remove_member]
19+
import com.google.api.services.cloudresourcemanager.model.Binding;
20+
import com.google.api.services.cloudresourcemanager.model.Policy;
21+
import java.util.List;
22+
23+
public class RemoveMember {
24+
25+
// Removes member from a role; removes binding if binding contains 0 members.
26+
public static void removeMember(Policy policy) {
27+
// policy = service.Projects.GetIAmPolicy(new GetIamPolicyRequest(), your-project-id).Execute();
28+
29+
String role = "roles/existing-role";
30+
String member = "user:[email protected]";
31+
32+
List<Binding> bindings = policy.getBindings();
33+
34+
for (Binding b : bindings) {
35+
if (b.getRole() == role) {
36+
if (b.getMembers().contains(member)) {
37+
b.getMembers().remove(member);
38+
System.out.println("Member " + member + " removed from " + role);
39+
}
40+
if (b.getMembers().size() == 0) {
41+
policy.getBindings().remove(b);
42+
}
43+
return;
44+
}
45+
}
46+
47+
System.out.println("Role not found in policy; member not removed");
48+
return;
49+
}
50+
}
51+
// [END iam_modify_policy_remove_member]
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
/* Copyright 2019 Google LLC
2+
*
3+
* Licensed under the Apache License, Version 2.0 (the "License");
4+
* you may not use this file except in compliance with the License.
5+
* You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software
10+
* distributed under the License is distributed on an "AS IS" BASIS,
11+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
* See the License for the specific language governing permissions and
13+
* limitations under the License.
14+
*/
15+
16+
package com.google.iam.snippets;
17+
18+
// [START iam_set_policy]
19+
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
20+
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
21+
import com.google.api.client.json.jackson2.JacksonFactory;
22+
import com.google.api.services.cloudresourcemanager.CloudResourceManager;
23+
import com.google.api.services.cloudresourcemanager.model.Policy;
24+
import com.google.api.services.cloudresourcemanager.model.SetIamPolicyRequest;
25+
import com.google.api.services.iam.v1.IamScopes;
26+
import java.io.IOException;
27+
import java.security.GeneralSecurityException;
28+
import java.util.Collections;
29+
30+
public class SetPolicy {
31+
32+
// Sets a project's policy.
33+
public static void setPolicy(Policy policy, String projectId) {
34+
// policy = service.Projects.GetIAmPolicy(new GetIamPolicyRequest(), your-project-id).Execute();
35+
// projectId = "my-project-id"
36+
37+
CloudResourceManager service = null;
38+
try {
39+
service = createCloudResourceManagerService();
40+
} catch (IOException | GeneralSecurityException e) {
41+
System.out.println("Unable to initialize service: \n" + e.toString());
42+
return;
43+
}
44+
45+
try {
46+
SetIamPolicyRequest request = new SetIamPolicyRequest();
47+
request.setPolicy(policy);
48+
Policy response = service.projects().setIamPolicy(projectId, request).execute();
49+
System.out.println("Policy set: " + response.toString());
50+
} catch (IOException e) {
51+
System.out.println("Unable to set policy: \n" + e.toString());
52+
}
53+
}
54+
55+
public static CloudResourceManager createCloudResourceManagerService()
56+
throws IOException, GeneralSecurityException {
57+
// Use the Application Default Credentials strategy for authentication. For more info, see:
58+
// https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
59+
GoogleCredential credential =
60+
GoogleCredential.getApplicationDefault()
61+
.createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
62+
63+
CloudResourceManager service =
64+
new CloudResourceManager.Builder(
65+
GoogleNetHttpTransport.newTrustedTransport(),
66+
JacksonFactory.getDefaultInstance(),
67+
credential)
68+
.setApplicationName("service-accounts")
69+
.build();
70+
return service;
71+
}
72+
}
73+
// [END iam_set_policy]
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
/* Copyright 2019 Google LLC
2+
*
3+
* Licensed under the Apache License, Version 2.0 (the "License");
4+
* you may not use this file except in compliance with the License.
5+
* You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software
10+
* distributed under the License is distributed on an "AS IS" BASIS,
11+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
* See the License for the specific language governing permissions and
13+
* limitations under the License.
14+
*/
15+
16+
package com.google.iam.snippets;
17+
18+
// [START iam-test-permissions]
19+
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
20+
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
21+
import com.google.api.client.json.jackson2.JacksonFactory;
22+
import com.google.api.services.cloudresourcemanager.CloudResourceManager;
23+
import com.google.api.services.cloudresourcemanager.model.TestIamPermissionsRequest;
24+
import com.google.api.services.cloudresourcemanager.model.TestIamPermissionsResponse;
25+
import com.google.api.services.iam.v1.IamScopes;
26+
import java.io.IOException;
27+
import java.security.GeneralSecurityException;
28+
import java.util.Arrays;
29+
import java.util.Collections;
30+
import java.util.List;
31+
32+
public class TestPermissions {
33+
34+
// Tests if the caller has the listed permissions.
35+
public static void testPermissions(String projectId) {
36+
// projectId = "my-project-id"
37+
38+
CloudResourceManager service = null;
39+
try {
40+
service = createCloudResourceManagerService();
41+
} catch (IOException | GeneralSecurityException e) {
42+
System.out.println("Unable to initialize service: \n" + e.toString());
43+
return;
44+
}
45+
46+
List<String> permissionsList =
47+
Arrays.asList("resourcemanager.projects.get", "resourcemanager.projects.delete");
48+
49+
TestIamPermissionsRequest requestBody =
50+
new TestIamPermissionsRequest().setPermissions(permissionsList);
51+
try {
52+
TestIamPermissionsResponse testIamPermissionsResponse =
53+
service.projects().testIamPermissions(projectId, requestBody).execute();
54+
55+
System.out.println(
56+
"Of the permissions listed in the request, the caller has the following: "
57+
+ testIamPermissionsResponse.getPermissions().toString());
58+
} catch (IOException e) {
59+
System.out.println("Unable to test permissions: \n" + e.toString());
60+
}
61+
}
62+
63+
public static CloudResourceManager createCloudResourceManagerService()
64+
throws IOException, GeneralSecurityException {
65+
// Use the Application Default Credentials strategy for authentication. For more info, see:
66+
// https://cloud.google.com/docs/authentication/production#finding_credentials_automatically
67+
GoogleCredential credential =
68+
GoogleCredential.getApplicationDefault()
69+
.createScoped(Collections.singleton(IamScopes.CLOUD_PLATFORM));
70+
71+
CloudResourceManager service =
72+
new CloudResourceManager.Builder(
73+
GoogleNetHttpTransport.newTrustedTransport(),
74+
JacksonFactory.getDefaultInstance(),
75+
credential)
76+
.setApplicationName("service-accounts")
77+
.build();
78+
return service;
79+
}
80+
}
81+
// [END iam-test-permissions]

0 commit comments

Comments
 (0)