diff --git a/samples/snippets/README.md b/samples/snippets/README.md new file mode 100644 index 0000000..0c5ea3d --- /dev/null +++ b/samples/snippets/README.md @@ -0,0 +1 @@ +The snippets have been migrated to GoogleCloudPlatform/python-docs-samples in PR: https://github.com/GoogleCloudPlatform/python-docs-samples/pull/8497 \ No newline at end of file diff --git a/samples/snippets/__init__.py b/samples/snippets/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/samples/snippets/conftest.py b/samples/snippets/conftest.py deleted file mode 100644 index 4fa0dea..0000000 --- a/samples/snippets/conftest.py +++ /dev/null @@ -1,56 +0,0 @@ -# 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 samples.snippets.create_deny_policy import create_deny_policy -from samples.snippets.delete_deny_policy import delete_deny_policy - -PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"] -GOOGLE_APPLICATION_CREDENTIALS = os.environ["GOOGLE_APPLICATION_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/samples/snippets/create_deny_policy.py b/samples/snippets/create_deny_policy.py deleted file mode 100644 index 569e55e..0000000 --- a/samples/snippets/create_deny_policy.py +++ /dev/null @@ -1,118 +0,0 @@ -# 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/samples/snippets/delete_deny_policy.py b/samples/snippets/delete_deny_policy.py deleted file mode 100644 index e7128dc..0000000 --- a/samples/snippets/delete_deny_policy.py +++ /dev/null @@ -1,62 +0,0 @@ -# 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/samples/snippets/get_deny_policy.py b/samples/snippets/get_deny_policy.py deleted file mode 100644 index 9f451fb..0000000 --- a/samples/snippets/get_deny_policy.py +++ /dev/null @@ -1,64 +0,0 @@ -# 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/samples/snippets/list_deny_policies.py b/samples/snippets/list_deny_policies.py deleted file mode 100644 index 106794f..0000000 --- a/samples/snippets/list_deny_policies.py +++ /dev/null @@ -1,65 +0,0 @@ -# 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/samples/snippets/noxfile.py b/samples/snippets/noxfile.py deleted file mode 100644 index de104db..0000000 --- a/samples/snippets/noxfile.py +++ /dev/null @@ -1,292 +0,0 @@ -# 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. - -from __future__ import print_function - -import glob -import os -from pathlib import Path -import sys -from typing import Callable, Dict, Optional - -import nox - -# WARNING - WARNING - WARNING - WARNING - WARNING -# WARNING - WARNING - WARNING - WARNING - WARNING -# DO NOT EDIT THIS FILE EVER! -# WARNING - WARNING - WARNING - WARNING - WARNING -# WARNING - WARNING - WARNING - WARNING - WARNING - -BLACK_VERSION = "black==22.3.0" -ISORT_VERSION = "isort==5.10.1" - -# Copy `noxfile_config.py` to your directory and modify it instead. - -# `TEST_CONFIG` dict is a configuration hook that allows users to -# modify the test configurations. The values here should be in sync -# with `noxfile_config.py`. Users will copy `noxfile_config.py` into -# their directory and modify it. - -TEST_CONFIG = { - # You can opt out from the test for specific Python versions. - "ignored_versions": [], - # Old samples are opted out of enforcing Python type hints - # All new samples should feature them - "enforce_type_hints": False, - # 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': 'BUILD_SPECIFIC_GCLOUD_PROJECT', - # If you need to use a specific version of pip, - # change pip_version_override to the string representation - # of the version number, for example, "20.2.4" - "pip_version_override": None, - # A dictionary you want to inject into your test. Don't put any - # secrets here. These values will override predefined values. - "envs": {}, -} - - -try: - # Ensure we can import noxfile_config in the project's directory. - sys.path.append(".") - from noxfile_config import TEST_CONFIG_OVERRIDE -except ImportError as e: - print("No user noxfile_config found: detail: {}".format(e)) - TEST_CONFIG_OVERRIDE = {} - -# Update the TEST_CONFIG with the user supplied values. -TEST_CONFIG.update(TEST_CONFIG_OVERRIDE) - - -def get_pytest_env_vars() -> Dict[str, str]: - """Returns a dict for pytest invocation.""" - ret = {} - - # Override the GCLOUD_PROJECT and the alias. - env_key = TEST_CONFIG["gcloud_project_env"] - # This should error out if not set. - ret["GOOGLE_CLOUD_PROJECT"] = os.environ[env_key] - - # Apply user supplied envs. - ret.update(TEST_CONFIG["envs"]) - return ret - - -# DO NOT EDIT - automatically generated. -# All versions used to test samples. -ALL_VERSIONS = ["3.7", "3.8", "3.9", "3.10", "3.11"] - -# Any default versions that should be ignored. -IGNORED_VERSIONS = TEST_CONFIG["ignored_versions"] - -TESTED_VERSIONS = sorted([v for v in ALL_VERSIONS if v not in IGNORED_VERSIONS]) - -INSTALL_LIBRARY_FROM_SOURCE = os.environ.get("INSTALL_LIBRARY_FROM_SOURCE", False) in ( - "True", - "true", -) - -# Error if a python version is missing -nox.options.error_on_missing_interpreters = True - -# -# Style Checks -# - - -# Linting with flake8. -# -# We ignore the following rules: -# E203: whitespace before ‘:’ -# E266: too many leading ‘#’ for block comment -# E501: line too long -# I202: Additional newline in a section of imports -# -# We also need to specify the rules which are ignored by default: -# ['E226', 'W504', 'E126', 'E123', 'W503', 'E24', 'E704', 'E121'] -FLAKE8_COMMON_ARGS = [ - "--show-source", - "--builtin=gettext", - "--max-complexity=20", - "--exclude=.nox,.cache,env,lib,generated_pb2,*_pb2.py,*_pb2_grpc.py", - "--ignore=E121,E123,E126,E203,E226,E24,E266,E501,E704,W503,W504,I202", - "--max-line-length=88", -] - - -@nox.session -def lint(session: nox.sessions.Session) -> None: - if not TEST_CONFIG["enforce_type_hints"]: - session.install("flake8") - else: - session.install("flake8", "flake8-annotations") - - args = FLAKE8_COMMON_ARGS + [ - ".", - ] - session.run("flake8", *args) - - -# -# Black -# - - -@nox.session -def blacken(session: nox.sessions.Session) -> None: - """Run black. Format code to uniform standard.""" - session.install(BLACK_VERSION) - python_files = [path for path in os.listdir(".") if path.endswith(".py")] - - session.run("black", *python_files) - - -# -# format = isort + black -# - - -@nox.session -def format(session: nox.sessions.Session) -> None: - """ - Run isort to sort imports. Then run black - to format code to uniform standard. - """ - session.install(BLACK_VERSION, ISORT_VERSION) - python_files = [path for path in os.listdir(".") if path.endswith(".py")] - - # Use the --fss option to sort imports using strict alphabetical order. - # See https://pycqa.github.io/isort/docs/configuration/options.html#force-sort-within-sections - session.run("isort", "--fss", *python_files) - session.run("black", *python_files) - - -# -# Sample Tests -# - - -PYTEST_COMMON_ARGS = ["--junitxml=sponge_log.xml"] - - -def _session_tests( - session: nox.sessions.Session, post_install: Callable = None -) -> None: - # check for presence of tests - test_list = glob.glob("**/*_test.py", recursive=True) + glob.glob( - "**/test_*.py", recursive=True - ) - test_list.extend(glob.glob("**/tests", recursive=True)) - - if len(test_list) == 0: - print("No tests found, skipping directory.") - return - - if TEST_CONFIG["pip_version_override"]: - pip_version = TEST_CONFIG["pip_version_override"] - session.install(f"pip=={pip_version}") - """Runs py.test for a particular project.""" - concurrent_args = [] - if os.path.exists("requirements.txt"): - if os.path.exists("constraints.txt"): - session.install("-r", "requirements.txt", "-c", "constraints.txt") - else: - session.install("-r", "requirements.txt") - with open("requirements.txt") as rfile: - packages = rfile.read() - - if os.path.exists("requirements-test.txt"): - if os.path.exists("constraints-test.txt"): - session.install("-r", "requirements-test.txt", "-c", "constraints-test.txt") - else: - session.install("-r", "requirements-test.txt") - with open("requirements-test.txt") as rtfile: - packages += rtfile.read() - - if INSTALL_LIBRARY_FROM_SOURCE: - session.install("-e", _get_repo_root()) - - if post_install: - post_install(session) - - if "pytest-parallel" in packages: - concurrent_args.extend(["--workers", "auto", "--tests-per-worker", "auto"]) - elif "pytest-xdist" in packages: - concurrent_args.extend(["-n", "auto"]) - - session.run( - "pytest", - *(PYTEST_COMMON_ARGS + session.posargs + concurrent_args), - # Pytest will return 5 when no tests are collected. This can happen - # on travis where slow and flaky tests are excluded. - # See http://doc.pytest.org/en/latest/_modules/_pytest/main.html - success_codes=[0, 5], - env=get_pytest_env_vars(), - ) - - -@nox.session(python=ALL_VERSIONS) -def py(session: nox.sessions.Session) -> None: - """Runs py.test for a sample using the specified version of Python.""" - if session.python in TESTED_VERSIONS: - _session_tests(session) - else: - session.skip( - "SKIPPED: {} tests are disabled for this sample.".format(session.python) - ) - - -# -# Readmegen -# - - -def _get_repo_root() -> Optional[str]: - """Returns the root folder of the project.""" - # Get root of this repository. Assume we don't have directories nested deeper than 10 items. - p = Path(os.getcwd()) - for i in range(10): - if p is None: - break - if Path(p / ".git").exists(): - return str(p) - # .git is not available in repos cloned via Cloud Build - # setup.py is always in the library's root, so use that instead - # https://github.com/googleapis/synthtool/issues/792 - if Path(p / "setup.py").exists(): - return str(p) - p = p.parent - raise Exception("Unable to detect repository root.") - - -GENERATED_READMES = sorted([x for x in Path(".").rglob("*.rst.in")]) - - -@nox.session -@nox.parametrize("path", GENERATED_READMES) -def readmegen(session: nox.sessions.Session, path: str) -> None: - """(Re-)generates the readme for a sample.""" - session.install("jinja2", "pyyaml") - dir_ = os.path.dirname(path) - - if os.path.exists(os.path.join(dir_, "requirements.txt")): - session.install("-r", os.path.join(dir_, "requirements.txt")) - - in_file = os.path.join(dir_, "README.rst.in") - session.run( - "python", _get_repo_root() + "/scripts/readme-gen/readme_gen.py", in_file - ) diff --git a/samples/snippets/noxfile_config.py b/samples/snippets/noxfile_config.py deleted file mode 100644 index e892b33..0000000 --- a/samples/snippets/noxfile_config.py +++ /dev/null @@ -1,38 +0,0 @@ -# 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/samples/snippets/requirements-test.txt b/samples/snippets/requirements-test.txt deleted file mode 100644 index 805eb2a..0000000 --- a/samples/snippets/requirements-test.txt +++ /dev/null @@ -1 +0,0 @@ -pytest==7.2.1 diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt deleted file mode 100644 index 9855243..0000000 --- a/samples/snippets/requirements.txt +++ /dev/null @@ -1 +0,0 @@ -google-cloud-iam==2.11.1 \ No newline at end of file diff --git a/samples/snippets/test_deny_policies.py b/samples/snippets/test_deny_policies.py deleted file mode 100644 index f6f50cb..0000000 --- a/samples/snippets/test_deny_policies.py +++ /dev/null @@ -1,51 +0,0 @@ -# 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 samples.snippets.get_deny_policy import get_deny_policy -from samples.snippets.list_deny_policies import list_deny_policy -from samples.snippets.update_deny_policy import update_deny_policy - -PROJECT_ID = os.environ["GOOGLE_CLOUD_PROJECT"] -GOOGLE_APPLICATION_CREDENTIALS = os.environ["GOOGLE_APPLICATION_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/samples/snippets/update_deny_policy.py b/samples/snippets/update_deny_policy.py deleted file mode 100644 index 3756c0b..0000000 --- a/samples/snippets/update_deny_policy.py +++ /dev/null @@ -1,112 +0,0 @@ -# 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]