Skip to content

Commit 79a0484

Browse files
docs(samples): add iam deny samples and test (#371)
* docs(samples): init add iam deny samples and test * docs(samples): added comments * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * docs(samples): add pom.xml and removed jupiter dependency * minor lro update and refactoring * added comments and minor refactoring * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * added region tags * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * updated acc to review comments * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com>
1 parent f582a18 commit 79a0484

File tree

7 files changed

+775
-0
lines changed

7 files changed

+775
-0
lines changed
Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<!--
3+
Copyright 2022 Google LLC
4+
5+
Licensed under the Apache License, Version 2.0 (the "License");
6+
you may not use this file except in compliance with the License.
7+
You may obtain a copy of the License at
8+
9+
http://www.apache.org/licenses/LICENSE-2.0
10+
11+
Unless required by applicable law or agreed to in writing, software
12+
distributed under the License is distributed on an "AS IS" BASIS,
13+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
See the License for the specific language governing permissions and
15+
limitations under the License.
16+
-->
17+
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
18+
xmlns="http://maven.apache.org/POM/4.0.0"
19+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
20+
<artifactId>iam-deny-samples</artifactId>
21+
<modelVersion>4.0.0</modelVersion>
22+
<version>1.0-SNAPSHOT</version>
23+
24+
<dependencies>
25+
26+
<dependency>
27+
<groupId>com.google.apis</groupId>
28+
<artifactId>google-api-services-cloudresourcemanager</artifactId>
29+
<version>v3-rev20211107-1.32.1</version>
30+
</dependency>
31+
<dependency>
32+
<groupId>com.google.auth</groupId>
33+
<artifactId>google-auth-library-oauth2-http</artifactId>
34+
<version>1.4.0</version>
35+
</dependency>
36+
<dependency>
37+
<groupId>com.google.http-client</groupId>
38+
<artifactId>google-http-client-jackson2</artifactId>
39+
<version>1.41.8</version>
40+
</dependency>
41+
<dependency>
42+
<groupId>com.google.apis</groupId>
43+
<artifactId>google-api-services-iam</artifactId>
44+
<version>v2beta-rev20220526-1.32.1</version>
45+
</dependency>
46+
<dependency>
47+
<groupId>com.google.apis</groupId>
48+
<artifactId>google-api-services-iamcredentials</artifactId>
49+
<version>v1-rev20211203-1.32.1</version>
50+
</dependency>
51+
52+
<!-- Test dependencies -->
53+
<dependency>
54+
<artifactId>truth</artifactId>
55+
<groupId>com.google.truth</groupId>
56+
<scope>test</scope>
57+
<version>1.1.3</version>
58+
</dependency>
59+
<dependency>
60+
<artifactId>junit</artifactId>
61+
<groupId>junit</groupId>
62+
<scope>test</scope>
63+
<version>4.13.2</version>
64+
</dependency>
65+
66+
</dependencies>
67+
68+
<dependencyManagement>
69+
<dependencies>
70+
<dependency>
71+
<artifactId>libraries-bom</artifactId>
72+
<groupId>com.google.cloud</groupId>
73+
<scope>import</scope>
74+
<type>pom</type>
75+
<version>25.0.0</version>
76+
</dependency>
77+
</dependencies>
78+
</dependencyManagement>
79+
80+
<!--
81+
The parent pom defines common style checks and testing strategies for our samples.
82+
Removing or replacing it should not affect the execution of the samples in anyway.
83+
-->
84+
<parent>
85+
<artifactId>shared-configuration</artifactId>
86+
<groupId>com.google.cloud.samples</groupId>
87+
<version>1.2.0</version>
88+
</parent>
89+
90+
<properties>
91+
<maven.compiler.source>11</maven.compiler.source>
92+
<maven.compiler.target>11</maven.compiler.target>
93+
</properties>
94+
95+
<groupId>gce-diregapic</groupId>
96+
97+
</project>
Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
/*
2+
* Copyright 2022 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
// [START iam_create_deny_policy]
18+
19+
import com.google.iam.v2beta.CreatePolicyRequest;
20+
import com.google.iam.v2beta.DenyRule;
21+
import com.google.iam.v2beta.PoliciesClient;
22+
import com.google.iam.v2beta.Policy;
23+
import com.google.iam.v2beta.PolicyRule;
24+
import com.google.longrunning.Operation;
25+
import com.google.type.Expr;
26+
import java.io.IOException;
27+
import java.net.URLEncoder;
28+
import java.nio.charset.StandardCharsets;
29+
import java.util.concurrent.ExecutionException;
30+
import java.util.concurrent.TimeUnit;
31+
import java.util.concurrent.TimeoutException;
32+
33+
public class CreateDenyPolicy {
34+
35+
public static void main(String[] args)
36+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
37+
// TODO(developer): Replace these variables before running the sample.
38+
// ID or number of the Google Cloud project you want to use.
39+
String projectId = "sitalakshmi-deny";
40+
41+
// Specify the id of the Deny policy you want to create.
42+
String policyId = "deny-policy-id-1";
43+
44+
createDenyPolicy(projectId, policyId);
45+
}
46+
47+
// Create a deny policy.
48+
// You can add deny policies to organizations, folders, and projects.
49+
// Each of these resources can have up to 5 deny policies.
50+
//
51+
// Deny policies contain deny rules, which specify the following:
52+
// 1. The permissions to deny and/or exempt.
53+
// 2. The principals that are denied, or exempted from denial.
54+
// 3. An optional condition on when to enforce the deny rules.
55+
public static void createDenyPolicy(String projectId, String policyId)
56+
throws IOException, ExecutionException, InterruptedException, TimeoutException {
57+
58+
try (PoliciesClient policiesClient = PoliciesClient.create()) {
59+
// Each deny policy is attached to an organization, folder, or project.
60+
// To work with deny policies, specify the attachment point.
61+
//
62+
// Its format can be one of the following:
63+
// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
64+
// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
65+
// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
66+
//
67+
// The attachment point is identified by its URL-encoded resource name.
68+
String urlEncodedResource =
69+
URLEncoder.encode(
70+
"cloudresourcemanager.googleapis.com/projects/", StandardCharsets.UTF_8);
71+
String attachmentPoint = String.format("%s%s", urlEncodedResource, projectId);
72+
73+
// Construct the full path of the resource to which the policy is attached.
74+
// Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
75+
String policyParent = String.format("policies/%s/denypolicies", attachmentPoint);
76+
77+
DenyRule denyRule =
78+
DenyRule.newBuilder()
79+
// Add one or more principals who should be denied the permissions specified in this
80+
// rule.
81+
// For more information on allowed values, see:
82+
// https://cloud.google.com/iam/docs/principal-identifiers
83+
.addDeniedPrincipals("principalSet://goog/public:all")
84+
85+
// Optionally, set the principals who should be exempted from the
86+
// list of denied principals. For example, if you want to deny certain permissions
87+
// to a group but exempt a few principals, then add those here.
88+
// .addExceptionPrincipals(
89+
// "principalSet://goog/group/project-admins@example.com")
90+
91+
// Set the permissions to deny.
92+
// The permission value is of the format: service_fqdn/resource.action
93+
// For the list of supported permissions, see:
94+
// https://cloud.google.com/iam/help/deny/supported-permissions
95+
.addDeniedPermissions("cloudresourcemanager.googleapis.com/projects.delete")
96+
97+
// Optionally, add the permissions to be exempted from this rule.
98+
// Meaning, the deny rule will not be applicable to these permissions.
99+
// .addExceptionPermissions("cloudresourcemanager.googleapis.com/projects.create")
100+
101+
// Set the condition which will enforce the deny rule. If this condition is true,
102+
// the deny rule will be applicable. Else, the rule will not be enforced.
103+
.setDenialCondition(
104+
Expr.newBuilder()
105+
// The expression uses Common Expression Language syntax (CEL).
106+
// Here we block access based on tags.
107+
//
108+
// A tag is a key-value pair that can be attached to an organization, folder,
109+
// or project. You can use deny policies to deny permissions based on tags
110+
// without adding an IAM Condition to every role grant.
111+
// For example, imagine that you tag all of your projects as dev, test, or
112+
// prod. You want only members of project-admins@example.com to be able to
113+
// perform operations on projects that are tagged prod.
114+
// To solve this problem, you create a deny rule that denies the
115+
// cloudresourcemanager.googleapis.com/projects.delete permission to everyone
116+
// except project-admins@example.com for resources that are tagged test.
117+
.setExpression("!resource.matchTag('12345678/env', 'test')")
118+
.setTitle("Only for test projects")
119+
.build())
120+
.build();
121+
122+
// Add the deny rule and a description for it.
123+
Policy policy =
124+
Policy.newBuilder()
125+
// Set the deny rule.
126+
.addRules(
127+
PolicyRule.newBuilder()
128+
// Set a description for the rule.
129+
.setDescription(
130+
"block all principals from deleting projects, unless the principal is a member of project-admins@example.com and the project being deleted has a tag with the value test")
131+
.setDenyRule(denyRule)
132+
.build())
133+
.build();
134+
135+
// Set the policy resource path, policy rules and a unique ID for the policy.
136+
CreatePolicyRequest createPolicyRequest =
137+
CreatePolicyRequest.newBuilder()
138+
.setParent(policyParent)
139+
.setPolicy(policy)
140+
.setPolicyId(policyId)
141+
.build();
142+
143+
// Build the create policy request.
144+
Operation operation =
145+
policiesClient
146+
.createPolicyCallable()
147+
.futureCall(createPolicyRequest)
148+
.get(3, TimeUnit.MINUTES);
149+
150+
// Wait for the operation to complete.
151+
if (!operation.getDone() || operation.hasError()) {
152+
System.out.println("Error in creating the policy " + operation.getError());
153+
return;
154+
}
155+
156+
// Retrieve the policy name.
157+
Policy response = policiesClient.getPolicy(String.format("%s/%s", policyParent, policyId));
158+
String policyName = response.getName();
159+
System.out.println(
160+
"Created the deny policy: " + policyName.substring(policyName.lastIndexOf("/") + 1));
161+
}
162+
}
163+
}
164+
// [END iam_create_deny_policy]
Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
/*
2+
* Copyright 2022 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
// [START iam_delete_deny_policy]
18+
19+
import com.google.iam.v2beta.DeletePolicyRequest;
20+
import com.google.iam.v2beta.PoliciesClient;
21+
import com.google.longrunning.Operation;
22+
import java.io.IOException;
23+
import java.net.URLEncoder;
24+
import java.nio.charset.StandardCharsets;
25+
import java.util.concurrent.ExecutionException;
26+
import java.util.concurrent.TimeUnit;
27+
import java.util.concurrent.TimeoutException;
28+
29+
public class DeleteDenyPolicy {
30+
31+
public static void main(String[] args)
32+
throws IOException, InterruptedException, ExecutionException, TimeoutException {
33+
// TODO(developer): Replace these variables before running the sample.
34+
35+
// ID or number of the Google Cloud project you want to use.
36+
String projectId = "your-google-cloud-project-id";
37+
38+
// Specify the ID of the deny policy you want to retrieve.
39+
String policyId = "deny-policy-id";
40+
41+
deleteDenyPolicy(projectId, policyId);
42+
}
43+
44+
// Delete the policy if you no longer want to enforce the rules in a deny policy.
45+
public static void deleteDenyPolicy(String projectId, String policyId)
46+
throws IOException, InterruptedException, ExecutionException, TimeoutException {
47+
try (PoliciesClient policiesClient = PoliciesClient.create()) {
48+
49+
// Each deny policy is attached to an organization, folder, or project.
50+
// To work with deny policies, specify the attachment point.
51+
//
52+
// Its format can be one of the following:
53+
// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
54+
// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
55+
// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
56+
//
57+
// The attachment point is identified by its URL-encoded resource name.
58+
String urlEncodedResource =
59+
URLEncoder.encode(
60+
"cloudresourcemanager.googleapis.com/projects/", StandardCharsets.UTF_8);
61+
String attachmentPoint = String.format("%s%s", urlEncodedResource, projectId);
62+
63+
// Construct the full path of the resource to which the policy is attached.
64+
// Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
65+
String policyParent = String.format("policies/%s/denypolicies/%s", attachmentPoint, policyId);
66+
67+
// Create the DeletePolicy request.
68+
DeletePolicyRequest deletePolicyRequest =
69+
DeletePolicyRequest.newBuilder().setName(policyParent).build();
70+
71+
// Delete the policy and wait for the operation to complete.
72+
Operation operation =
73+
policiesClient
74+
.deletePolicyCallable()
75+
.futureCall(deletePolicyRequest)
76+
.get(3, TimeUnit.MINUTES);
77+
78+
if (!operation.getDone() || operation.hasError()) {
79+
System.out.println("Error in deleting the policy " + operation.getError());
80+
return;
81+
}
82+
83+
System.out.println("Deleted the deny policy: " + policyId);
84+
}
85+
}
86+
}
87+
// [END iam_delete_deny_policy]

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy