Skip to content
This repository has been archived by the owner on Sep 16, 2023. It is now read-only.

Commit

Permalink
docs(samples): add iam deny samples and test (#371)
Browse files Browse the repository at this point in the history
* 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>
  • Loading branch information
Sita04 and gcf-owl-bot[bot] committed Jul 8, 2022
1 parent 6e10d73 commit c503444
Show file tree
Hide file tree
Showing 7 changed files with 775 additions and 0 deletions.
97 changes: 97 additions & 0 deletions samples/cloud-client/snippets/pom.xml
@@ -0,0 +1,97 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2022 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.
-->
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<artifactId>iam-deny-samples</artifactId>
<modelVersion>4.0.0</modelVersion>
<version>1.0-SNAPSHOT</version>

<dependencies>

<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-cloudresourcemanager</artifactId>
<version>v3-rev20211107-1.32.1</version>
</dependency>
<dependency>
<groupId>com.google.auth</groupId>
<artifactId>google-auth-library-oauth2-http</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>com.google.http-client</groupId>
<artifactId>google-http-client-jackson2</artifactId>
<version>1.41.8</version>
</dependency>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-iam</artifactId>
<version>v2beta-rev20220526-1.32.1</version>
</dependency>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-iamcredentials</artifactId>
<version>v1-rev20211203-1.32.1</version>
</dependency>

<!-- Test dependencies -->
<dependency>
<artifactId>truth</artifactId>
<groupId>com.google.truth</groupId>
<scope>test</scope>
<version>1.1.3</version>
</dependency>
<dependency>
<artifactId>junit</artifactId>
<groupId>junit</groupId>
<scope>test</scope>
<version>4.13.2</version>
</dependency>

</dependencies>

<dependencyManagement>
<dependencies>
<dependency>
<artifactId>libraries-bom</artifactId>
<groupId>com.google.cloud</groupId>
<scope>import</scope>
<type>pom</type>
<version>25.0.0</version>
</dependency>
</dependencies>
</dependencyManagement>

<!--
The parent pom defines common style checks and testing strategies for our samples.
Removing or replacing it should not affect the execution of the samples in anyway.
-->
<parent>
<artifactId>shared-configuration</artifactId>
<groupId>com.google.cloud.samples</groupId>
<version>1.2.0</version>
</parent>

<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>

<groupId>gce-diregapic</groupId>

</project>
164 changes: 164 additions & 0 deletions samples/cloud-client/snippets/src/main/java/CreateDenyPolicy.java
@@ -0,0 +1,164 @@
/*
* Copyright 2022 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.
*/

// [START iam_create_deny_policy]

import com.google.iam.v2beta.CreatePolicyRequest;
import com.google.iam.v2beta.DenyRule;
import com.google.iam.v2beta.PoliciesClient;
import com.google.iam.v2beta.Policy;
import com.google.iam.v2beta.PolicyRule;
import com.google.longrunning.Operation;
import com.google.type.Expr;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateDenyPolicy {

public static void main(String[] args)
throws IOException, ExecutionException, InterruptedException, TimeoutException {
// TODO(developer): Replace these variables before running the sample.
// ID or number of the Google Cloud project you want to use.
String projectId = "sitalakshmi-deny";

// Specify the id of the Deny policy you want to create.
String policyId = "deny-policy-id-1";

createDenyPolicy(projectId, policyId);
}

// Create a deny policy.
// You can add deny policies to organizations, folders, and projects.
// Each of these resources can have up to 5 deny policies.
//
// Deny policies contain deny rules, which specify the following:
// 1. The permissions to deny and/or exempt.
// 2. The principals that are denied, or exempted from denial.
// 3. An optional condition on when to enforce the deny rules.
public static void createDenyPolicy(String projectId, String policyId)
throws IOException, ExecutionException, InterruptedException, TimeoutException {

try (PoliciesClient policiesClient = PoliciesClient.create()) {
// Each deny policy is attached to an organization, folder, or project.
// To work with deny policies, specify the attachment point.
//
// Its format can be one of the following:
// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
//
// The attachment point is identified by its URL-encoded resource name.
String urlEncodedResource =
URLEncoder.encode(
"cloudresourcemanager.googleapis.com/projects/", StandardCharsets.UTF_8);
String attachmentPoint = String.format("%s%s", urlEncodedResource, projectId);

// Construct the full path of the resource to which the policy is attached.
// Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
String policyParent = String.format("policies/%s/denypolicies", attachmentPoint);

DenyRule denyRule =
DenyRule.newBuilder()
// Add one or more principals who should be denied the permissions specified in this
// rule.
// For more information on allowed values, see:
// https://cloud.google.com/iam/docs/principal-identifiers
.addDeniedPrincipals("principalSet://goog/public:all")

// Optionally, set the principals who should be exempted from the
// list of denied principals. For example, if you want to deny certain permissions
// to a group but exempt a few principals, then add those here.
// .addExceptionPrincipals(
// "principalSet://goog/group/project-admins@example.com")

// Set the permissions to deny.
// The permission value is of the format: service_fqdn/resource.action
// For the list of supported permissions, see:
// https://cloud.google.com/iam/help/deny/supported-permissions
.addDeniedPermissions("cloudresourcemanager.googleapis.com/projects.delete")

// Optionally, add the permissions to be exempted from this rule.
// Meaning, the deny rule will not be applicable to these permissions.
// .addExceptionPermissions("cloudresourcemanager.googleapis.com/projects.create")

// Set the condition which will enforce the deny rule. If this condition is true,
// the deny rule will be applicable. Else, the rule will not be enforced.
.setDenialCondition(
Expr.newBuilder()
// The expression uses Common Expression Language syntax (CEL).
// Here we block access based on tags.
//
// A tag is a key-value pair that can be attached to an organization, folder,
// or project. You can use deny policies to deny permissions based on tags
// without adding an IAM Condition to every role grant.
// For example, imagine that you tag all of your projects as dev, test, or
// prod. You want only members of project-admins@example.com to be able to
// perform operations on projects that are tagged prod.
// To solve this problem, you create a deny rule that denies the
// cloudresourcemanager.googleapis.com/projects.delete permission to everyone
// except project-admins@example.com for resources that are tagged test.
.setExpression("!resource.matchTag('12345678/env', 'test')")
.setTitle("Only for test projects")
.build())
.build();

// Add the deny rule and a description for it.
Policy policy =
Policy.newBuilder()
// Set the deny rule.
.addRules(
PolicyRule.newBuilder()
// Set a description for the rule.
.setDescription(
"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")
.setDenyRule(denyRule)
.build())
.build();

// Set the policy resource path, policy rules and a unique ID for the policy.
CreatePolicyRequest createPolicyRequest =
CreatePolicyRequest.newBuilder()
.setParent(policyParent)
.setPolicy(policy)
.setPolicyId(policyId)
.build();

// Build the create policy request.
Operation operation =
policiesClient
.createPolicyCallable()
.futureCall(createPolicyRequest)
.get(3, TimeUnit.MINUTES);

// Wait for the operation to complete.
if (!operation.getDone() || operation.hasError()) {
System.out.println("Error in creating the policy " + operation.getError());
return;
}

// Retrieve the policy name.
Policy response = policiesClient.getPolicy(String.format("%s/%s", policyParent, policyId));
String policyName = response.getName();
System.out.println(
"Created the deny policy: " + policyName.substring(policyName.lastIndexOf("/") + 1));
}
}
}
// [END iam_create_deny_policy]
87 changes: 87 additions & 0 deletions samples/cloud-client/snippets/src/main/java/DeleteDenyPolicy.java
@@ -0,0 +1,87 @@
/*
* Copyright 2022 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.
*/

// [START iam_delete_deny_policy]

import com.google.iam.v2beta.DeletePolicyRequest;
import com.google.iam.v2beta.PoliciesClient;
import com.google.longrunning.Operation;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class DeleteDenyPolicy {

public static void main(String[] args)
throws IOException, InterruptedException, ExecutionException, TimeoutException {
// TODO(developer): Replace these variables before running the sample.

// ID or number of the Google Cloud project you want to use.
String projectId = "your-google-cloud-project-id";

// Specify the ID of the deny policy you want to retrieve.
String policyId = "deny-policy-id";

deleteDenyPolicy(projectId, policyId);
}

// Delete the policy if you no longer want to enforce the rules in a deny policy.
public static void deleteDenyPolicy(String projectId, String policyId)
throws IOException, InterruptedException, ExecutionException, TimeoutException {
try (PoliciesClient policiesClient = PoliciesClient.create()) {

// Each deny policy is attached to an organization, folder, or project.
// To work with deny policies, specify the attachment point.
//
// Its format can be one of the following:
// 1. cloudresourcemanager.googleapis.com/organizations/ORG_ID
// 2. cloudresourcemanager.googleapis.com/folders/FOLDER_ID
// 3. cloudresourcemanager.googleapis.com/projects/PROJECT_ID
//
// The attachment point is identified by its URL-encoded resource name.
String urlEncodedResource =
URLEncoder.encode(
"cloudresourcemanager.googleapis.com/projects/", StandardCharsets.UTF_8);
String attachmentPoint = String.format("%s%s", urlEncodedResource, projectId);

// Construct the full path of the resource to which the policy is attached.
// Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}"
String policyParent = String.format("policies/%s/denypolicies/%s", attachmentPoint, policyId);

// Create the DeletePolicy request.
DeletePolicyRequest deletePolicyRequest =
DeletePolicyRequest.newBuilder().setName(policyParent).build();

// Delete the policy and wait for the operation to complete.
Operation operation =
policiesClient
.deletePolicyCallable()
.futureCall(deletePolicyRequest)
.get(3, TimeUnit.MINUTES);

if (!operation.getDone() || operation.hasError()) {
System.out.println("Error in deleting the policy " + operation.getError());
return;
}

System.out.println("Deleted the deny policy: " + policyId);
}
}
}
// [END iam_delete_deny_policy]

0 comments on commit c503444

Please sign in to comment.