From cc1f05e2c17a27b8723b72097bd093e9b580a8d2 Mon Sep 17 00:00:00 2001 From: Don McCasland Date: Wed, 25 Jan 2023 11:51:16 -0800 Subject: [PATCH] feat: migrate code from googleapis/python-iam (#8497) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat!: migrate to microgenerator (#26) * docs(samples): add deny samples and tests (#209) * docs(samples): init add deny samples and tests * docs(samples): added requirements.txt * docs(samples): minor update and refactoring * added nox files * 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 * added region tags * modified comments acc to review * modified comments acc to review * updated env var * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * modified acc to review comments * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * modified acc to review comments * added init.py * updated acc to review comments Co-authored-by: Owl Bot Co-authored-by: nicain Co-authored-by: Anthonios Partheniou * chore(deps): update all dependencies (#217) * chore(deps): update all dependencies * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * revert Co-authored-by: Owl Bot Co-authored-by: Anthonios Partheniou * chore(deps): update all dependencies (#218) * chore(deps): update all dependencies * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * revert Co-authored-by: Owl Bot Co-authored-by: Anthonios Partheniou * chore(deps): update dependency google-cloud-iam to v2.8.2 (#225) * chore: detect samples tests in nested directories (#236) Source-Link: https://github.com/googleapis/synthtool/commit/50db768f450a50d7c1fd62513c113c9bb96fd434 Post-Processor: gcr.io/cloud-devrel-public-resources/owlbot-python:latest@sha256:e09366bdf0fd9c8976592988390b24d53583dd9f002d476934da43725adbb978 * feat: Add client for IAM Deny v2 API (#230) * feat: Create the public IAM Deny v2 API PiperOrigin-RevId: 470600752 Source-Link: https://github.com/googleapis/googleapis/commit/dac66f65613ec8ce243622f18725d160aebd9ced Source-Link: https://github.com/googleapis/googleapis-gen/commit/729529edc103e45087ffae8353eaf009ad7fe8c2 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNzI5NTI5ZWRjMTAzZTQ1MDg3ZmZhZTgzNTNlYWYwMDlhZDdmZThjMiJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * regenerate files using cl/470713093 * workaround docstring formatting issue * add pytest to samples CI * lint * fix import statement in samples/snippets * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * docs(samples): migrate samples from iam_v2beta to iam_v2 * update required checks to include samples * use GOOGLE_CLOUD_PROJECT * fix imports in samples/snippets * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * add pytest * chore(python): prepare for release of the iam/v2 python client PiperOrigin-RevId: 471240188 Source-Link: https://github.com/googleapis/googleapis/commit/ea847a1bdd969fced5b13cfa70a0119cd1652cd1 Source-Link: https://github.com/googleapis/googleapis-gen/commit/6f1e4cd013ab2914773826e68b2a2d0763030a39 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNmYxZTRjZDAxM2FiMjkxNDc3MzgyNmU2OGIyYTJkMDc2MzAzMGEzOSJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * feat: Bump gapic-generator-python version to 1.3.0 PiperOrigin-RevId: 472561635 Source-Link: https://github.com/googleapis/googleapis/commit/332ecf599f8e747d8d1213b77ae7db26eff12814 Source-Link: https://github.com/googleapis/googleapis-gen/commit/4313d682880fd9d7247291164d4e9d3d5bd9f177 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiNDMxM2Q2ODI4ODBmZDlkNzI0NzI5MTE2NGQ0ZTlkM2Q1YmQ5ZjE3NyJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * chore: use gapic-generator-python 1.3.1 PiperOrigin-RevId: 472772457 Source-Link: https://github.com/googleapis/googleapis/commit/855b74d203deeb0f7a0215f9454cdde62a1f9b86 Source-Link: https://github.com/googleapis/googleapis-gen/commit/b64b1e7da3e138f15ca361552ef0545e54891b4f Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYjY0YjFlN2RhM2UxMzhmMTVjYTM2MTU1MmVmMDU0NWU1NDg5MWI0ZiJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * fix: integrate gapic-generator-python-1.4.1 and enable more py_test targets PiperOrigin-RevId: 473833416 Source-Link: https://github.com/googleapis/googleapis/commit/565a5508869557a3228b871101e4e4ebd8f93d11 Source-Link: https://github.com/googleapis/googleapis-gen/commit/1ee1a06c6de3ca8b843572c1fde0548f84236989 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiMWVlMWEwNmM2ZGUzY2E4Yjg0MzU3MmMxZmRlMDU0OGY4NDIzNjk4OSJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * updated test to delete stale policies and avoid quota error * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * feat!: remove ListApplicablePolicies PiperOrigin-RevId: 475955031 Source-Link: https://github.com/googleapis/googleapis/commit/65376f43de1a43dcd40b21a5c2f844bde0049604 Source-Link: https://github.com/googleapis/googleapis-gen/commit/c8504e97891ed9e664cf68270d7e61bec160fe57 Copy-Tag: eyJwIjoiLmdpdGh1Yi8uT3dsQm90LnlhbWwiLCJoIjoiYzg1MDRlOTc4OTFlZDllNjY0Y2Y2ODI3MGQ3ZTYxYmVjMTYwZmU1NyJ9 * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * samples: wait for the operation to complete * samples: minor refactoring * use project `python-docs-samples-tests` Co-authored-by: Owl Bot Co-authored-by: Anthonios Partheniou Co-authored-by: Sita Lakshmi Sangameswaran Co-authored-by: SitaLakshmi * chore(deps): update all dependencies (#244) * removing noxfile.py, adding CODEOWNERS and blunderbuss config * fixing up test infra * test infra fix * testing with secrets Co-authored-by: arithmetic1728 <58957152+arithmetic1728@users.noreply.github.com> Co-authored-by: Sita Lakshmi Sangameswaran Co-authored-by: Owl Bot Co-authored-by: nicain Co-authored-by: Anthonios Partheniou Co-authored-by: WhiteSource Renovate Co-authored-by: WhiteSource Renovate Co-authored-by: gcf-owl-bot[bot] <78513119+gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: SitaLakshmi Co-authored-by: Maciej Strzelczyk Co-authored-by: Karl Weinmeister <11586922+kweinmeister@users.noreply.github.com> --- .github/CODEOWNERS | 3 +- .github/blunderbuss.yml | 4 + iam/cloud-client/AUTHORING_GUIDE.md | 1 + iam/cloud-client/CONTRIBUTING.md | 1 + iam/cloud-client/snippets/__init__.py | 0 iam/cloud-client/snippets/conftest.py | 56 +++++++++ .../snippets/create_deny_policy.py | 118 ++++++++++++++++++ .../snippets/delete_deny_policy.py | 62 +++++++++ iam/cloud-client/snippets/get_deny_policy.py | 64 ++++++++++ .../snippets/list_deny_policies.py | 65 ++++++++++ iam/cloud-client/snippets/noxfile_config.py | 38 ++++++ .../snippets/requirements-test.txt | 1 + iam/cloud-client/snippets/requirements.txt | 1 + .../snippets/test_deny_policies.py | 51 ++++++++ .../snippets/update_deny_policy.py | 112 +++++++++++++++++ 15 files changed, 576 insertions(+), 1 deletion(-) create mode 100644 iam/cloud-client/AUTHORING_GUIDE.md create mode 100644 iam/cloud-client/CONTRIBUTING.md create mode 100644 iam/cloud-client/snippets/__init__.py create mode 100644 iam/cloud-client/snippets/conftest.py create mode 100644 iam/cloud-client/snippets/create_deny_policy.py create mode 100644 iam/cloud-client/snippets/delete_deny_policy.py create mode 100644 iam/cloud-client/snippets/get_deny_policy.py create mode 100644 iam/cloud-client/snippets/list_deny_policies.py create mode 100644 iam/cloud-client/snippets/noxfile_config.py create mode 100644 iam/cloud-client/snippets/requirements-test.txt create mode 100644 iam/cloud-client/snippets/requirements.txt create mode 100644 iam/cloud-client/snippets/test_deny_policies.py create mode 100644 iam/cloud-client/snippets/update_deny_policy.py diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 43b9385f66e9..e1e3c80032af 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -53,7 +53,8 @@ /functions/**/* @GoogleCloudPlatform/aap-dpes @GoogleCloudPlatform/python-samples-reviewers /functions/spanner/* @GoogleCloudPlatform/api-spanner-python @GoogleCloudPlatform/python-samples-reviewers /healthcare/**/* @noerog @GoogleCloudPlatform/python-samples-reviewers -/iam/**/* @GoogleCloudPlatform/python-samples-reviewers +/iam/api-client/**/* @GoogleCloudPlatform/python-samples-reviewers +/iam/cloud-client/**/* @GoogleCloudPlatform/dee-infra @GoogleCloudPlatform/python-samples-reviewers /iap/**/* @GoogleCloudPlatform/python-samples-reviewers /iot/**/* @gcseh @GoogleCloudPlatform/api-iot @GoogleCloudPlatform/python-samples-reviewers /jobs/**/* @GoogleCloudPlatform/python-samples-reviewers diff --git a/.github/blunderbuss.yml b/.github/blunderbuss.yml index 618cb98e7fa1..868de1d881d8 100644 --- a/.github/blunderbuss.yml +++ b/.github/blunderbuss.yml @@ -78,6 +78,10 @@ assign_issues_by: - 'api: healthcare' to: - noerog +- labels: + - 'api: iam' + to: + - GoogleCloudPlatform/dee-infra - labels: - 'api: iot' - 'api: cloudiot' diff --git a/iam/cloud-client/AUTHORING_GUIDE.md b/iam/cloud-client/AUTHORING_GUIDE.md new file mode 100644 index 000000000000..55c97b32f4c1 --- /dev/null +++ b/iam/cloud-client/AUTHORING_GUIDE.md @@ -0,0 +1 @@ +See https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/AUTHORING_GUIDE.md \ No newline at end of file diff --git a/iam/cloud-client/CONTRIBUTING.md b/iam/cloud-client/CONTRIBUTING.md new file mode 100644 index 000000000000..34c882b6f1a3 --- /dev/null +++ b/iam/cloud-client/CONTRIBUTING.md @@ -0,0 +1 @@ +See https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/CONTRIBUTING.md \ No newline at end of file diff --git a/iam/cloud-client/snippets/__init__.py b/iam/cloud-client/snippets/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/iam/cloud-client/snippets/conftest.py b/iam/cloud-client/snippets/conftest.py new file mode 100644 index 000000000000..bf2d233b9892 --- /dev/null +++ b/iam/cloud-client/snippets/conftest.py @@ -0,0 +1,56 @@ +# 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. + +import os +import re +import uuid + +from google.cloud import iam_v2 +from google.cloud.iam_v2 import types +import pytest +from snippets.create_deny_policy import create_deny_policy +from snippets.delete_deny_policy import delete_deny_policy + +PROJECT_ID = os.environ["IAM_PROJECT_ID"] +GOOGLE_APPLICATION_CREDENTIALS = os.environ["IAM_CREDENTIALS"] + + +@pytest.fixture +def deny_policy(capsys: "pytest.CaptureFixture[str]") -> None: + policy_id = f"test-deny-policy-{uuid.uuid4()}" + + # Delete any existing policies. Otherwise it might throw quota issue. + delete_existing_deny_policies(PROJECT_ID, "test-deny-policy") + + # Create the Deny policy. + create_deny_policy(PROJECT_ID, policy_id) + + yield policy_id + + # Delete the Deny policy and assert if deleted. + delete_deny_policy(PROJECT_ID, policy_id) + out, _ = capsys.readouterr() + assert re.search(f"Deleted the deny policy: {policy_id}", out) + + +def delete_existing_deny_policies(project_id: str, delete_name_prefix: str) -> None: + policies_client = iam_v2.PoliciesClient() + + attachment_point = f"cloudresourcemanager.googleapis.com%2Fprojects%2F{project_id}" + + request = types.ListPoliciesRequest() + request.parent = f"policies/{attachment_point}/denypolicies" + for policy in policies_client.list_policies(request=request): + if delete_name_prefix in policy.name: + delete_deny_policy(PROJECT_ID, str(policy.name).rsplit("/", 1)[-1]) diff --git a/iam/cloud-client/snippets/create_deny_policy.py b/iam/cloud-client/snippets/create_deny_policy.py new file mode 100644 index 000000000000..569e55e77a75 --- /dev/null +++ b/iam/cloud-client/snippets/create_deny_policy.py @@ -0,0 +1,118 @@ +# 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. + +# This file contains code samples that demonstrate how to create IAM deny policies. + +# [START iam_create_deny_policy] + + +def create_deny_policy(project_id: str, policy_id: str) -> None: + from google.cloud import iam_v2 + from google.cloud.iam_v2 import types + + """ + 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. + + Params: + project_id: ID or number of the Google Cloud project you want to use. + policy_id: Specify the ID of the deny policy you want to create. + """ + policies_client = iam_v2.PoliciesClient() + + # 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. Hence, replace + # the "/" with "%2F". + attachment_point = f"cloudresourcemanager.googleapis.com%2Fprojects%2F{project_id}" + + deny_rule = types.DenyRule() + # 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/help/deny/principal-identifiers + deny_rule.denied_principals = ["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. + # deny_rule.exception_principals = ["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 + deny_rule.denied_permissions = [ + "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. + # deny_rule.exception_permissions = ["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. + # The expression uses Common Expression Language syntax (CEL). + # Here we block access based on tags. + # + # Here, we 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. + # A tag is a key-value pair that can be attached to an organization, folder, or project. + # For more info, see: https://cloud.google.com/iam/docs/deny-access#create-deny-policy + deny_rule.denial_condition = { + "expression": "!resource.matchTag('12345678/env', 'test')" + } + + # Add the deny rule and a description for it. + policy_rule = types.PolicyRule() + policy_rule.description = "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" + policy_rule.deny_rule = deny_rule + + policy = types.Policy() + policy.display_name = "Restrict project deletion access" + policy.rules = [policy_rule] + + # Set the policy resource path, policy rules and a unique ID for the policy. + request = types.CreatePolicyRequest() + # Construct the full path of the resource's deny policies. + # Its format is: "policies/{attachmentPoint}/denypolicies" + request.parent = f"policies/{attachment_point}/denypolicies" + request.policy = policy + request.policy_id = policy_id + + # Build the create policy request and wait for the operation to complete. + result = policies_client.create_policy(request=request).result() + print(f"Created the deny policy: {result.name.rsplit('/')[-1]}") + + +if __name__ == "__main__": + import uuid + + # Your Google Cloud project ID. + project_id = "your-google-cloud-project-id" + # Any unique ID (0 to 63 chars) starting with a lowercase letter. + policy_id = f"deny-{uuid.uuid4()}" + + # Test the policy lifecycle. + create_deny_policy(project_id, policy_id) + +# [END iam_create_deny_policy] diff --git a/iam/cloud-client/snippets/delete_deny_policy.py b/iam/cloud-client/snippets/delete_deny_policy.py new file mode 100644 index 000000000000..e7128dc6e325 --- /dev/null +++ b/iam/cloud-client/snippets/delete_deny_policy.py @@ -0,0 +1,62 @@ +# 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. + +# This file contains code samples that demonstrate how to delete IAM deny policies. + +# [START iam_delete_deny_policy] +def delete_deny_policy(project_id: str, policy_id: str) -> None: + from google.cloud import iam_v2 + from google.cloud.iam_v2 import types + + """ + Delete the policy if you no longer want to enforce the rules in a deny policy. + + project_id: ID or number of the Google Cloud project you want to use. + policy_id: The ID of the deny policy you want to retrieve. + """ + policies_client = iam_v2.PoliciesClient() + + # 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. Hence, replace + # the "/" with "%2F". + attachment_point = f"cloudresourcemanager.googleapis.com%2Fprojects%2F{project_id}" + + request = types.DeletePolicyRequest() + # Construct the full path of the policy. + # Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}" + request.name = f"policies/{attachment_point}/denypolicies/{policy_id}" + + # Create the DeletePolicy request. + result = policies_client.delete_policy(request=request).result() + print(f"Deleted the deny policy: {result.name.rsplit('/')[-1]}") + + +if __name__ == "__main__": + import uuid + + # Your Google Cloud project ID. + project_id = "your-google-cloud-project-id" + # Any unique ID (0 to 63 chars) starting with a lowercase letter. + policy_id = f"deny-{uuid.uuid4()}" + + delete_deny_policy(project_id, policy_id) + +# [END iam_delete_deny_policy] diff --git a/iam/cloud-client/snippets/get_deny_policy.py b/iam/cloud-client/snippets/get_deny_policy.py new file mode 100644 index 000000000000..9f451fb65f9c --- /dev/null +++ b/iam/cloud-client/snippets/get_deny_policy.py @@ -0,0 +1,64 @@ +# 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. + +# This file contains code samples that demonstrate how to get IAM deny policies. + +# [START iam_get_deny_policy] +from google.cloud import iam_v2 +from google.cloud.iam_v2 import Policy, types + + +def get_deny_policy(project_id: str, policy_id: str) -> Policy: + """ + Retrieve the deny policy given the project ID and policy ID. + + project_id: ID or number of the Google Cloud project you want to use. + policy_id: The ID of the deny policy you want to retrieve. + """ + policies_client = iam_v2.PoliciesClient() + + # 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. Hence, replace + # the "/" with "%2F". + attachment_point = f"cloudresourcemanager.googleapis.com%2Fprojects%2F{project_id}" + + request = types.GetPolicyRequest() + # Construct the full path of the policy. + # Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}" + request.name = f"policies/{attachment_point}/denypolicies/{policy_id}" + + # Execute the GetPolicy request. + policy = policies_client.get_policy(request=request) + print(f"Retrieved the deny policy: {policy_id} : {policy}") + return policy + + +if __name__ == "__main__": + import uuid + + # Your Google Cloud project ID. + project_id = "your-google-cloud-project-id" + # Any unique ID (0 to 63 chars) starting with a lowercase letter. + policy_id = f"deny-{uuid.uuid4()}" + + policy = get_deny_policy(project_id, policy_id) + +# [END iam_get_deny_policy] diff --git a/iam/cloud-client/snippets/list_deny_policies.py b/iam/cloud-client/snippets/list_deny_policies.py new file mode 100644 index 000000000000..106794f52beb --- /dev/null +++ b/iam/cloud-client/snippets/list_deny_policies.py @@ -0,0 +1,65 @@ +# 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. + +# This file contains code samples that demonstrate how to list IAM deny policies. + +# [START iam_list_deny_policy] +def list_deny_policy(project_id: str) -> None: + from google.cloud import iam_v2 + from google.cloud.iam_v2 import types + + """ + List all the deny policies that are attached to a resource. + A resource can have up to 5 deny policies. + + project_id: ID or number of the Google Cloud project you want to use. + """ + policies_client = iam_v2.PoliciesClient() + + # 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. Hence, replace + # the "/" with "%2F". + attachment_point = f"cloudresourcemanager.googleapis.com%2Fprojects%2F{project_id}" + + request = types.ListPoliciesRequest() + # Construct the full path of the resource's deny policies. + # Its format is: "policies/{attachmentPoint}/denypolicies" + request.parent = f"policies/{attachment_point}/denypolicies" + + # Create a list request and iterate over the returned policies. + policies = policies_client.list_policies(request=request) + + for policy in policies: + print(policy.name) + print("Listed all deny policies") + + +if __name__ == "__main__": + import uuid + + # Your Google Cloud project ID. + project_id = "your-google-cloud-project-id" + # Any unique ID (0 to 63 chars) starting with a lowercase letter. + policy_id = f"deny-{uuid.uuid4()}" + + list_deny_policy(project_id) + +# [END iam_list_deny_policy] diff --git a/iam/cloud-client/snippets/noxfile_config.py b/iam/cloud-client/snippets/noxfile_config.py new file mode 100644 index 000000000000..e892b338fcea --- /dev/null +++ b/iam/cloud-client/snippets/noxfile_config.py @@ -0,0 +1,38 @@ +# 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. + +# Default TEST_CONFIG_OVERRIDE for python repos. + +# You can copy this file into your directory, then it will be inported from +# the noxfile.py. + +# The source of truth: +# https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/noxfile_config.py + +TEST_CONFIG_OVERRIDE = { + # You can opt out from the test for specific Python versions. + "ignored_versions": ["2.7"], + # Old samples are opted out of enforcing Python type hints + # All new samples should feature them + "enforce_type_hints": True, + # An envvar key for determining the project id to use. Change it + # to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a + # build specific Cloud project. You can also use your own string + # to use your own Cloud project. + # "gcloud_project_env": "GOOGLE_CLOUD_PROJECT", + "gcloud_project_env": "GOOGLE_CLOUD_PROJECT", + # A dictionary you want to inject into your test. Don't put any + # secrets here. These values will override predefined values. + "envs": {}, +} diff --git a/iam/cloud-client/snippets/requirements-test.txt b/iam/cloud-client/snippets/requirements-test.txt new file mode 100644 index 000000000000..49780e035690 --- /dev/null +++ b/iam/cloud-client/snippets/requirements-test.txt @@ -0,0 +1 @@ +pytest==7.2.0 diff --git a/iam/cloud-client/snippets/requirements.txt b/iam/cloud-client/snippets/requirements.txt new file mode 100644 index 000000000000..0e8c7f30f27d --- /dev/null +++ b/iam/cloud-client/snippets/requirements.txt @@ -0,0 +1 @@ +google-cloud-iam==2.9.0 \ No newline at end of file diff --git a/iam/cloud-client/snippets/test_deny_policies.py b/iam/cloud-client/snippets/test_deny_policies.py new file mode 100644 index 000000000000..620261e2f356 --- /dev/null +++ b/iam/cloud-client/snippets/test_deny_policies.py @@ -0,0 +1,51 @@ +# 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. + +import os +import re + +import pytest +from snippets.get_deny_policy import get_deny_policy +from snippets.list_deny_policies import list_deny_policy +from snippets.update_deny_policy import update_deny_policy + +PROJECT_ID = os.environ["IAM_PROJECT_ID"] +GOOGLE_APPLICATION_CREDENTIALS = os.environ["IAM_CREDENTIALS"] + + +def test_retrieve_policy( + capsys: "pytest.CaptureFixture[str]", deny_policy: str +) -> None: + # Test policy retrieval, given the policy id. + get_deny_policy(PROJECT_ID, deny_policy) + out, _ = capsys.readouterr() + assert re.search(f"Retrieved the deny policy: {deny_policy}", out) + + +def test_list_policies(capsys: "pytest.CaptureFixture[str]", deny_policy: str) -> None: + # Check if the created policy is listed. + list_deny_policy(PROJECT_ID) + out, _ = capsys.readouterr() + assert re.search(deny_policy, out) + assert re.search("Listed all deny policies", out) + + +def test_update_deny_policy( + capsys: "pytest.CaptureFixture[str]", deny_policy: str +) -> None: + # Check if the policy rule is updated. + policy = get_deny_policy(PROJECT_ID, deny_policy) + update_deny_policy(PROJECT_ID, deny_policy, policy.etag) + out, _ = capsys.readouterr() + assert re.search(f"Updated the deny policy: {deny_policy}", out) diff --git a/iam/cloud-client/snippets/update_deny_policy.py b/iam/cloud-client/snippets/update_deny_policy.py new file mode 100644 index 000000000000..3756c0bdecb6 --- /dev/null +++ b/iam/cloud-client/snippets/update_deny_policy.py @@ -0,0 +1,112 @@ +# 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. + +# This file contains code samples that demonstrate how to update IAM deny policies. + +# [START iam_update_deny_policy] +def update_deny_policy(project_id: str, policy_id: str, etag: str) -> None: + from google.cloud import iam_v2 + from google.cloud.iam_v2 import types + + """ + Update the deny rules and/ or its display name after policy creation. + + project_id: ID or number of the Google Cloud project you want to use. + + policy_id: The ID of the deny policy you want to retrieve. + + etag: Etag field that identifies the policy version. The etag changes each time + you update the policy. Get the etag of an existing policy by performing a GetPolicy request. + """ + policies_client = iam_v2.PoliciesClient() + + # 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. Hence, replace + # the "/" with "%2F". + attachment_point = f"cloudresourcemanager.googleapis.com%2Fprojects%2F{project_id}" + + deny_rule = types.DenyRule() + + # 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/help/deny/principal-identifiers + deny_rule.denied_principals = ["principalSet://goog/public:all"] + + # Optionally, set the principals who should be exempted from the list of principals added in "DeniedPrincipals". + # Example, if you want to deny certain permissions to a group but exempt a few principals, then add those here. + # deny_rule.exception_principals = ["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 + deny_rule.denied_permissions = [ + "cloudresourcemanager.googleapis.com/projects.delete" + ] + + # Add the permissions to be exempted from this rule. + # Meaning, the deny rule will not be applicable to these permissions. + # deny_rule.exception_permissions = ["cloudresourcemanager.googleapis.com/projects.get"] + + # 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. + # + # The expression uses Common Expression Language syntax (CEL). Here we block access based on tags. + # + # Here, we 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 prod. + # A tag is a key-value pair that can be attached to an organization, folder, or project. + # For more info, see: https://cloud.google.com/iam/docs/deny-access#create-deny-policy + deny_rule.denial_condition = { + "expression": "!resource.matchTag('12345678/env', 'prod')" + } + + # Set the rule description and deny rule to update. + policy_rule = types.PolicyRule() + policy_rule.description = "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 prod" + policy_rule.deny_rule = deny_rule + + # Set the policy resource path, version (etag) and the updated deny rules. + policy = types.Policy() + # Construct the full path of the policy. + # Its format is: "policies/{attachmentPoint}/denypolicies/{policyId}" + policy.name = f"policies/{attachment_point}/denypolicies/{policy_id}" + policy.etag = etag + policy.rules = [policy_rule] + + # Create the update policy request. + request = types.UpdatePolicyRequest() + request.policy = policy + + result = policies_client.update_policy(request=request).result() + print(f"Updated the deny policy: {result.name.rsplit('/')[-1]}") + + +if __name__ == "__main__": + import uuid + + # Your Google Cloud project ID. + project_id = "your-google-cloud-project-id" + # Any unique ID (0 to 63 chars) starting with a lowercase letter. + policy_id = f"deny-{uuid.uuid4()}" + # Get the etag by performing a Get policy request. + etag = "etag" + + update_deny_policy(project_id, policy_id, etag) + +# [END iam_update_deny_policy]