diff --git a/.kokoro/docker/samples/Dockerfile b/.kokoro/docker/samples/Dockerfile new file mode 100644 index 0000000..3cc47de --- /dev/null +++ b/.kokoro/docker/samples/Dockerfile @@ -0,0 +1,36 @@ +# Copyright 2021 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. + +# Use the python-docs-samples iamge as a base: +# https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/.kokoro/docker/Dockerfile +FROM gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker + +# Install Chrome. +RUN curl https://dl-ssl.google.com/linux/linux_signing_key.pub -o /tmp/google.pub \ + && cat /tmp/google.pub | apt-key add -; rm /tmp/google.pub \ + && echo 'deb http://dl.google.com/linux/chrome/deb/ stable main' > /etc/apt/sources.list.d/google.list \ + && mkdir -p /usr/share/desktop-directories \ + && apt-get -y update && apt-get install -y google-chrome-stable + +# Disable the SUID sandbox so that Chrome can launch without being in a privileged container. +RUN dpkg-divert --add --rename --divert /opt/google/chrome/google-chrome.real /opt/google/chrome/google-chrome \ + && echo "#!/bin/bash\nexec /opt/google/chrome/google-chrome.real --no-sandbox --disable-setuid-sandbox \"\$@\"" > /opt/google/chrome/google-chrome \ + && chmod 755 /opt/google/chrome/google-chrome + +# Install Chrome Driver. +RUN mkdir -p /opt/selenium \ + && curl http://chromedriver.storage.googleapis.com/`curl -sS chromedriver.storage.googleapis.com/LATEST_RELEASE`/chromedriver_linux64.zip -o /opt/selenium/chromedriver_linux64.zip \ + && cd /opt/selenium; unzip /opt/selenium/chromedriver_linux64.zip; rm -rf chromedriver_linux64.zip; ln -fs /opt/selenium/chromedriver /usr/local/bin/chromedriver; + +CMD ["python3.6"] \ No newline at end of file diff --git a/.kokoro/samples/lint/common.cfg b/.kokoro/samples/lint/common.cfg index 9c1f551..0bb8c19 100644 --- a/.kokoro/samples/lint/common.cfg +++ b/.kokoro/samples/lint/common.cfg @@ -18,10 +18,15 @@ env_vars: { value: "github/python-recaptcha-enterprise/.kokoro/test-samples.sh" } -# Configure the docker image for kokoro-trampoline. env_vars: { key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker" + value: "gcr.io/cloud-devrel-kokoro-resources/python-recaptcha-enterprise-samples-docker" +} + +# Configure the docker image for kokoro-trampoline. +env_vars: { + key: "TRAMPOLINE_DOCKERFILE" + value: ".kokoro/docker/samples/Dockerfile" } # Download secrets for samples diff --git a/.kokoro/samples/python3.10/common.cfg b/.kokoro/samples/python3.10/common.cfg index 653825f..6555f4d 100644 --- a/.kokoro/samples/python3.10/common.cfg +++ b/.kokoro/samples/python3.10/common.cfg @@ -24,10 +24,15 @@ env_vars: { value: "github/python-recaptcha-enterprise/.kokoro/test-samples.sh" } -# Configure the docker image for kokoro-trampoline. env_vars: { key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker" + value: "gcr.io/cloud-devrel-kokoro-resources/python-recaptcha-enterprise-samples-docker" +} + +# Configure the docker image for kokoro-trampoline. +env_vars: { + key: "TRAMPOLINE_DOCKERFILE" + value: ".kokoro/docker/samples/Dockerfile" } # Download secrets for samples diff --git a/.kokoro/samples/python3.10/periodic-head.cfg b/.kokoro/samples/python3.10/periodic-head.cfg index 14ad83d..4f55dae 100644 --- a/.kokoro/samples/python3.10/periodic-head.cfg +++ b/.kokoro/samples/python3.10/periodic-head.cfg @@ -9,3 +9,9 @@ env_vars: { key: "TRAMPOLINE_BUILD_FILE" value: "github/python-recaptcha-enterprise/.kokoro/test-samples-against-head.sh" } + +# Upload the docker image after successful builds. +env_vars: { + key: "TRAMPOLINE_IMAGE_UPLOAD" + value: "true" +} diff --git a/.kokoro/samples/python3.10/periodic.cfg b/.kokoro/samples/python3.10/periodic.cfg index 71cd1e5..4c4f37a 100644 --- a/.kokoro/samples/python3.10/periodic.cfg +++ b/.kokoro/samples/python3.10/periodic.cfg @@ -4,3 +4,9 @@ env_vars: { key: "INSTALL_LIBRARY_FROM_SOURCE" value: "False" } + +# Upload the docker image after successful builds. +env_vars: { + key: "TRAMPOLINE_IMAGE_UPLOAD" + value: "true" +} diff --git a/.kokoro/samples/python3.6/common.cfg b/.kokoro/samples/python3.6/common.cfg index 1deec64..28a3202 100644 --- a/.kokoro/samples/python3.6/common.cfg +++ b/.kokoro/samples/python3.6/common.cfg @@ -24,10 +24,15 @@ env_vars: { value: "github/python-recaptcha-enterprise/.kokoro/test-samples.sh" } -# Configure the docker image for kokoro-trampoline. env_vars: { key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker" + value: "gcr.io/cloud-devrel-kokoro-resources/python-recaptcha-enterprise-samples-docker" +} + +# Configure the docker image for kokoro-trampoline. +env_vars: { + key: "TRAMPOLINE_DOCKERFILE" + value: ".kokoro/docker/samples/Dockerfile" } # Download secrets for samples diff --git a/.kokoro/samples/python3.6/periodic-head.cfg b/.kokoro/samples/python3.6/periodic-head.cfg index 14ad83d..4f55dae 100644 --- a/.kokoro/samples/python3.6/periodic-head.cfg +++ b/.kokoro/samples/python3.6/periodic-head.cfg @@ -9,3 +9,9 @@ env_vars: { key: "TRAMPOLINE_BUILD_FILE" value: "github/python-recaptcha-enterprise/.kokoro/test-samples-against-head.sh" } + +# Upload the docker image after successful builds. +env_vars: { + key: "TRAMPOLINE_IMAGE_UPLOAD" + value: "true" +} diff --git a/.kokoro/samples/python3.6/periodic.cfg b/.kokoro/samples/python3.6/periodic.cfg index 71cd1e5..4c4f37a 100644 --- a/.kokoro/samples/python3.6/periodic.cfg +++ b/.kokoro/samples/python3.6/periodic.cfg @@ -4,3 +4,9 @@ env_vars: { key: "INSTALL_LIBRARY_FROM_SOURCE" value: "False" } + +# Upload the docker image after successful builds. +env_vars: { + key: "TRAMPOLINE_IMAGE_UPLOAD" + value: "true" +} diff --git a/.kokoro/samples/python3.7/common.cfg b/.kokoro/samples/python3.7/common.cfg index c15e5f0..d0dd036 100644 --- a/.kokoro/samples/python3.7/common.cfg +++ b/.kokoro/samples/python3.7/common.cfg @@ -24,10 +24,15 @@ env_vars: { value: "github/python-recaptcha-enterprise/.kokoro/test-samples.sh" } -# Configure the docker image for kokoro-trampoline. env_vars: { key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker" + value: "gcr.io/cloud-devrel-kokoro-resources/python-recaptcha-enterprise-samples-docker" +} + +# Configure the docker image for kokoro-trampoline. +env_vars: { + key: "TRAMPOLINE_DOCKERFILE" + value: ".kokoro/docker/samples/Dockerfile" } # Download secrets for samples diff --git a/.kokoro/samples/python3.7/periodic.cfg b/.kokoro/samples/python3.7/periodic.cfg index 71cd1e5..4c4f37a 100644 --- a/.kokoro/samples/python3.7/periodic.cfg +++ b/.kokoro/samples/python3.7/periodic.cfg @@ -4,3 +4,9 @@ env_vars: { key: "INSTALL_LIBRARY_FROM_SOURCE" value: "False" } + +# Upload the docker image after successful builds. +env_vars: { + key: "TRAMPOLINE_IMAGE_UPLOAD" + value: "true" +} diff --git a/.kokoro/samples/python3.8/common.cfg b/.kokoro/samples/python3.8/common.cfg index 293b6b3..bb65f54 100644 --- a/.kokoro/samples/python3.8/common.cfg +++ b/.kokoro/samples/python3.8/common.cfg @@ -24,10 +24,15 @@ env_vars: { value: "github/python-recaptcha-enterprise/.kokoro/test-samples.sh" } -# Configure the docker image for kokoro-trampoline. env_vars: { key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker" + value: "gcr.io/cloud-devrel-kokoro-resources/python-recaptcha-enterprise-samples-docker" +} + +# Configure the docker image for kokoro-trampoline. +env_vars: { + key: "TRAMPOLINE_DOCKERFILE" + value: ".kokoro/docker/samples/Dockerfile" } # Download secrets for samples diff --git a/.kokoro/samples/python3.8/periodic-head.cfg b/.kokoro/samples/python3.8/periodic-head.cfg index 14ad83d..4f55dae 100644 --- a/.kokoro/samples/python3.8/periodic-head.cfg +++ b/.kokoro/samples/python3.8/periodic-head.cfg @@ -9,3 +9,9 @@ env_vars: { key: "TRAMPOLINE_BUILD_FILE" value: "github/python-recaptcha-enterprise/.kokoro/test-samples-against-head.sh" } + +# Upload the docker image after successful builds. +env_vars: { + key: "TRAMPOLINE_IMAGE_UPLOAD" + value: "true" +} diff --git a/.kokoro/samples/python3.8/periodic.cfg b/.kokoro/samples/python3.8/periodic.cfg index 71cd1e5..4c4f37a 100644 --- a/.kokoro/samples/python3.8/periodic.cfg +++ b/.kokoro/samples/python3.8/periodic.cfg @@ -4,3 +4,9 @@ env_vars: { key: "INSTALL_LIBRARY_FROM_SOURCE" value: "False" } + +# Upload the docker image after successful builds. +env_vars: { + key: "TRAMPOLINE_IMAGE_UPLOAD" + value: "true" +} diff --git a/.kokoro/samples/python3.9/common.cfg b/.kokoro/samples/python3.9/common.cfg index 170f6ef..c922225 100644 --- a/.kokoro/samples/python3.9/common.cfg +++ b/.kokoro/samples/python3.9/common.cfg @@ -24,10 +24,15 @@ env_vars: { value: "github/python-recaptcha-enterprise/.kokoro/test-samples.sh" } -# Configure the docker image for kokoro-trampoline. env_vars: { key: "TRAMPOLINE_IMAGE" - value: "gcr.io/cloud-devrel-kokoro-resources/python-samples-testing-docker" + value: "gcr.io/cloud-devrel-kokoro-resources/python-recaptcha-enterprise-samples-docker" +} + +# Configure the docker image for kokoro-trampoline. +env_vars: { + key: "TRAMPOLINE_DOCKERFILE" + value: ".kokoro/docker/samples/Dockerfile" } # Download secrets for samples diff --git a/.kokoro/samples/python3.9/periodic-head.cfg b/.kokoro/samples/python3.9/periodic-head.cfg index 14ad83d..4f55dae 100644 --- a/.kokoro/samples/python3.9/periodic-head.cfg +++ b/.kokoro/samples/python3.9/periodic-head.cfg @@ -9,3 +9,9 @@ env_vars: { key: "TRAMPOLINE_BUILD_FILE" value: "github/python-recaptcha-enterprise/.kokoro/test-samples-against-head.sh" } + +# Upload the docker image after successful builds. +env_vars: { + key: "TRAMPOLINE_IMAGE_UPLOAD" + value: "true" +} diff --git a/.kokoro/samples/python3.9/periodic.cfg b/.kokoro/samples/python3.9/periodic.cfg index 71cd1e5..4c4f37a 100644 --- a/.kokoro/samples/python3.9/periodic.cfg +++ b/.kokoro/samples/python3.9/periodic.cfg @@ -4,3 +4,9 @@ env_vars: { key: "INSTALL_LIBRARY_FROM_SOURCE" value: "False" } + +# Upload the docker image after successful builds. +env_vars: { + key: "TRAMPOLINE_IMAGE_UPLOAD" + value: "true" +} diff --git a/owlbot.py b/owlbot.py index 5feaa1d..cbfa79e 100644 --- a/owlbot.py +++ b/owlbot.py @@ -39,7 +39,7 @@ # ---------------------------------------------------------------------------- # Add templated files # ---------------------------------------------------------------------------- -templated_files = common.py_library(cov_level=98, microgenerator=True) +templated_files = common.py_library(cov_level=98, microgenerator=True, custom_samples_dockerfile=True) s.move( templated_files, excludes=[".coveragerc"] diff --git a/samples/snippets/create_assessment.py b/samples/snippets/create_assessment.py new file mode 100644 index 0000000..ecda1e9 --- /dev/null +++ b/samples/snippets/create_assessment.py @@ -0,0 +1,82 @@ +# Copyright 2021 Google Inc. All Rights Reserved. +# +# 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 recaptcha_enterprise_create_assessment] +from google.cloud import recaptchaenterprise_v1 + + +def create_assessment( + project_id: str, recaptcha_site_key: str, token: str, recaptcha_action: str +) -> None: + """ Create an assessment to analyze the risk of a UI action. + Args: + project_id: GCloud Project ID + recaptcha_site_key: Site key obtained by registering a domain/app to use recaptcha services. + token: The token obtained from the client on passing the recaptchaSiteKey. + recaptcha_action: Action name corresponding to the token. + """ + + # TODO(developer): Replace these variables before running the sample. + # Specify a name for this assessment. + assessment_name = "assessment_name" + + client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient() + + # Set the properties of the event to be tracked. + event = recaptchaenterprise_v1.Event() + event.site_key = recaptcha_site_key + event.token = token + + assessment = recaptchaenterprise_v1.Assessment() + assessment.event = event + assessment.name = assessment_name + + project_name = f"projects/{project_id}" + + # Build the assessment request. + request = recaptchaenterprise_v1.CreateAssessmentRequest() + request.assessment = assessment + request.parent = project_name + + response = client.create_assessment(request) + + # Check if the token is valid. + if not response.token_properties.valid: + print( + "The CreateAssessment call failed because the token was " + + "invalid for for the following reasons: " + + str(response.token_properties.invalid_reason) + ) + return + + # Check if the expected action was executed. + if response.token_properties.action != recaptcha_action: + print( + "The action attribute in your reCAPTCHA tag does" + + "not match the action you are expecting to score" + ) + return + else: + # Get the risk score and the reason(s) + # For more information on interpreting the assessment, + # see: https://cloud.google.com/recaptcha-enterprise/docs/interpret-assessment + for reason in response.risk_analysis.reasons: + print(reason) + print( + "The reCAPTCHA score for this token is: " + + str(response.risk_analysis.score) + ) + + +# [END recaptcha_enterprise_create_assessment] diff --git a/samples/snippets/create_site_key.py b/samples/snippets/create_site_key.py new file mode 100644 index 0000000..6e89343 --- /dev/null +++ b/samples/snippets/create_site_key.py @@ -0,0 +1,66 @@ +# Copyright 2021 Google Inc. All Rights Reserved. +# +# 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 recaptcha_enterprise_create_site_key] +from google.cloud import recaptchaenterprise_v1 + + +def create_site_key(project_id: str, domain_name: str) -> str: + """Create reCAPTCHA Site key which binds a domain name to a unique key. + Args: + project_id : GCloud Project ID. + domain_name: Specify the domain name in which the reCAPTCHA should be activated. + """ + client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient() + + # Set the type of the reCAPTCHA to be displayed. + # For different types, see: https://cloud.google.com/recaptcha-enterprise/docs/keys + web_settings = recaptchaenterprise_v1.WebKeySettings() + web_settings.allowed_domains.append(domain_name) + web_settings.allow_amp_traffic = False + web_settings.integration_type = web_settings.IntegrationType.SCORE + + key = recaptchaenterprise_v1.Key() + key.display_name = "any descriptive name for the key" + key.web_settings = web_settings + + # Create the request. + request = recaptchaenterprise_v1.CreateKeyRequest() + request.parent = f"projects/{project_id}" + request.key = key + + # Get the name of the created reCAPTCHA site key. + response = client.create_key(request) + recaptcha_site_key = response.name.rsplit("/", maxsplit=1)[1] + print("reCAPTCHA Site key created successfully. Site Key: " + recaptcha_site_key) + return recaptcha_site_key + + +# [END recaptcha_enterprise_create_site_key] + +if __name__ == "__main__": + import google.auth + import google.auth.exceptions + + # TODO(developer): Replace the below variables before running + try: + default_project_id = google.auth.default()[1] + domain_name = "localhost" + except google.auth.exceptions.DefaultCredentialsError: + print( + "Please use `gcloud auth application-default login` " + "or set GOOGLE_APPLICATION_CREDENTIALS to use this script." + ) + else: + create_site_key(default_project_id, domain_name) diff --git a/samples/snippets/delete_site_key.py b/samples/snippets/delete_site_key.py new file mode 100644 index 0000000..f9f9fb6 --- /dev/null +++ b/samples/snippets/delete_site_key.py @@ -0,0 +1,57 @@ +# Copyright 2021 Google Inc. All Rights Reserved. +# +# 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 recaptcha_enterprise_delete_site_key] +from google.cloud import recaptchaenterprise_v1 + + +def delete_site_key(project_id: str, recaptcha_site_key: str) -> None: + """ Delete the given reCAPTCHA site key present under the project ID. + + Args: + project_id : GCloud Project ID. + recaptcha_site_key: Specify the key ID to be deleted. + """ + + client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient() + + # Construct the key details. + key_name = f"projects/{project_id}/keys/{recaptcha_site_key}" + + # Set the project ID and reCAPTCHA site key. + request = recaptchaenterprise_v1.DeleteKeyRequest() + request.name = key_name + + client.delete_key(request) + print("reCAPTCHA Site key deleted successfully ! ") + + +# [END recaptcha_enterprise_delete_site_key] + + +if __name__ == "__main__": + import google.auth + import google.auth.exceptions + + # TODO(developer): Replace the below variables before running + try: + default_project_id = google.auth.default()[1] + recaptcha_site_key = "recaptcha_site_key" + except google.auth.exceptions.DefaultCredentialsError: + print( + "Please use `gcloud auth application-default login` " + "or set GOOGLE_APPLICATION_CREDENTIALS to use this script." + ) + else: + delete_site_key(default_project_id, recaptcha_site_key) diff --git a/samples/snippets/get_site_key.py b/samples/snippets/get_site_key.py new file mode 100644 index 0000000..6d9eb84 --- /dev/null +++ b/samples/snippets/get_site_key.py @@ -0,0 +1,57 @@ +# Copyright 2021 Google Inc. All Rights Reserved. +# +# 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 recaptcha_enterprise_get_site_key] +from google.cloud import recaptchaenterprise_v1 + + +def get_site_key(project_id: str, recaptcha_site_key: str) -> None: + """ + Get the reCAPTCHA site key present under the project ID. + + Args: + project_id: GCloud Project ID. + recaptcha_site_key: Specify the site key to get the details. + """ + + client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient() + + # Construct the key details. + key_name = f"projects/{project_id}/keys/{recaptcha_site_key}" + + request = recaptchaenterprise_v1.GetKeyRequest() + request.name = key_name + + key = client.get_key(request) + print("Successfully obtained the key !" + key.name) + + +# [END recaptcha_enterprise_get_site_key] + + +if __name__ == "__main__": + import google.auth + import google.auth.exceptions + + # TODO(developer): Replace the below variables before running + try: + default_project_id = google.auth.default()[1] + recaptcha_site_key = "recaptcha_site_key" + except google.auth.exceptions.DefaultCredentialsError: + print( + "Please use `gcloud auth application-default login` " + "or set GOOGLE_APPLICATION_CREDENTIALS to use this script." + ) + else: + get_site_key(default_project_id, recaptcha_site_key) diff --git a/samples/snippets/list_site_keys.py b/samples/snippets/list_site_keys.py new file mode 100644 index 0000000..4510a9c --- /dev/null +++ b/samples/snippets/list_site_keys.py @@ -0,0 +1,56 @@ +# Copyright 2021 Google Inc. All Rights Reserved. +# +# 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 recaptcha_enterprise_list_site_keys] +from google.cloud import recaptchaenterprise_v1 + + +def list_site_keys(project_id: str) -> None: + """ List all keys present under the given project ID. + + Args: + project_id: GCloud Project ID. + """ + + project_name = f"projects/{project_id}" + + client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient() + + # Set the project id to list the keys present in it. + request = recaptchaenterprise_v1.ListKeysRequest() + request.parent = project_name + + response = client.list_keys(request) + print("Listing reCAPTCHA site keys: ") + for i, key in enumerate(response): + print(f"{str(i)}. {key.name}") + + +# [END recaptcha_enterprise_list_site_keys] + + +if __name__ == "__main__": + import google.auth + import google.auth.exceptions + + # TODO(developer): Replace the below variables before running + try: + default_project_id = google.auth.default()[1] + except google.auth.exceptions.DefaultCredentialsError: + print( + "Please use `gcloud auth application-default login` " + "or set GOOGLE_APPLICATION_CREDENTIALS to use this script." + ) + else: + list_site_keys(default_project_id) diff --git a/samples/snippets/noxfile.py b/samples/snippets/noxfile.py new file mode 100644 index 0000000..93a9122 --- /dev/null +++ b/samples/snippets/noxfile.py @@ -0,0 +1,270 @@ +# 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 os +from pathlib import Path +import sys +from typing import Callable, Dict, List, 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==19.10b0" + +# 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.6", "3.7", "3.8", "3.9", "3.10"] + +# 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 +# + + +def _determine_local_import_names(start_dir: str) -> List[str]: + """Determines all import names that should be considered "local". + + This is used when running the linter to insure that import order is + properly checked. + """ + file_ext_pairs = [os.path.splitext(path) for path in os.listdir(start_dir)] + return [ + basename + for basename, extension in file_ext_pairs + if extension == ".py" + or os.path.isdir(os.path.join(start_dir, basename)) + and basename not in ("__pycache__") + ] + + +# 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", + "--import-order-style=google", + "--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", "flake8-import-order") + else: + session.install("flake8", "flake8-import-order", "flake8-annotations") + + local_names = _determine_local_import_names(".") + args = FLAKE8_COMMON_ARGS + [ + "--application-import-names", + ",".join(local_names), + ".", + ] + session.run("flake8", *args) + + +# +# Black +# + + +@nox.session +def blacken(session: nox.sessions.Session) -> None: + session.install(BLACK_VERSION) + python_files = [path for path in os.listdir(".") if path.endswith(".py")] + + 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: + 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.""" + 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") + + 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") + + if INSTALL_LIBRARY_FROM_SOURCE: + session.install("-e", _get_repo_root()) + + if post_install: + post_install(session) + + session.run( + "pytest", + *(PYTEST_COMMON_ARGS + session.posargs), + # 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 new file mode 100644 index 0000000..cfbd02d --- /dev/null +++ b/samples/snippets/noxfile_config.py @@ -0,0 +1,38 @@ +# Copyright 2021 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 imported 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": "BUILD_SPECIFIC_GCLOUD_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 new file mode 100644 index 0000000..9e45473 --- /dev/null +++ b/samples/snippets/requirements-test.txt @@ -0,0 +1,4 @@ +selenium==3.141.0 +Flask==2.0.1 +pytest==6.2.4 +pytest-flask==1.2.0 \ No newline at end of file diff --git a/samples/snippets/requirements.txt b/samples/snippets/requirements.txt new file mode 100644 index 0000000..3886b89 --- /dev/null +++ b/samples/snippets/requirements.txt @@ -0,0 +1 @@ +google-cloud-recaptcha-enterprise==1.0.0 \ No newline at end of file diff --git a/samples/snippets/templates/index.html b/samples/snippets/templates/index.html new file mode 100644 index 0000000..df77d5a --- /dev/null +++ b/samples/snippets/templates/index.html @@ -0,0 +1,92 @@ + + + + + + + reCAPTCHA-Enterprise + + + + + +
+ + + + + + + +
+
+ +
+ + \ No newline at end of file diff --git a/samples/snippets/test_create_assessment.py b/samples/snippets/test_create_assessment.py new file mode 100644 index 0000000..fc1cdac --- /dev/null +++ b/samples/snippets/test_create_assessment.py @@ -0,0 +1,113 @@ +# Copyright 2021 Google Inc. All Rights Reserved. +# +# 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 time +import typing + +from _pytest.capture import CaptureFixture +from flask import Flask, render_template, url_for +import pytest +from selenium import webdriver +from selenium.webdriver.chrome.webdriver import WebDriver + +import create_assessment + +# TODO(developer): Replace these variables before running the sample. +from create_site_key import create_site_key +from delete_site_key import delete_site_key + +GOOGLE_CLOUD_PROJECT = os.environ["GOOGLE_CLOUD_PROJECT"] +DOMAIN_NAME = "localhost" + + +@pytest.fixture(scope="session") +def app() -> Flask: + app = Flask(__name__) + + @app.route("/assess/", methods=["GET"]) + def assess(site_key: str) -> str: + return render_template("index.html", site_key=site_key) + + @app.route("/", methods=["GET"]) + def index() -> str: + return "Helloworld!" + + return app + + +@pytest.fixture(scope="module") +def browser() -> WebDriver: + chrome_options = webdriver.ChromeOptions() + chrome_options.add_argument('--no-sandbox') + chrome_options.add_argument('--window-size=1420,1080') + chrome_options.add_argument('--headless') + chrome_options.add_argument('--disable-gpu') + browser = webdriver.Chrome(chrome_options=chrome_options) + yield browser + browser.close() + + +@pytest.fixture(scope="module") +def recaptcha_site_key() -> str: + recaptcha_site_key = create_site_key( + project_id=GOOGLE_CLOUD_PROJECT, domain_name=DOMAIN_NAME + ) + yield recaptcha_site_key + delete_site_key( + project_id=GOOGLE_CLOUD_PROJECT, recaptcha_site_key=recaptcha_site_key + ) + + +@pytest.mark.usefixtures("live_server") +def test_create_assessment( + capsys: CaptureFixture, recaptcha_site_key: str, browser: WebDriver +) -> None: + token, action = get_token(recaptcha_site_key, browser) + assess_token(recaptcha_site_key, token=token, action=action) + out, _ = capsys.readouterr() + assert re.search("The reCAPTCHA score for this token is: ", out) + score = out.rsplit(":", maxsplit=1)[1].strip() + set_score(browser, score) + + +def get_token(recaptcha_site_key: str, browser: WebDriver) -> typing.Tuple: + browser.get(url_for("assess", site_key=recaptcha_site_key, _external=True)) + time.sleep(5) + + browser.find_element_by_id("username").send_keys("username") + browser.find_element_by_id("password").send_keys("password") + browser.find_element_by_id("recaptchabutton").click() + + # Timeout of 5 seconds + time.sleep(5) + + element = browser.find_element_by_css_selector("#assessment") + token = element.get_attribute("data-token") + action = element.get_attribute("data-action") + return token, action + + +def assess_token(recaptcha_site_key: str, token: str, action: str) -> None: + create_assessment.create_assessment( + project_id=GOOGLE_CLOUD_PROJECT, + recaptcha_site_key=recaptcha_site_key, + token=token, + recaptcha_action=action, + ) + + +def set_score(browser: WebDriver, score: str) -> None: + browser.find_element_by_css_selector("#assessment").send_keys(score) diff --git a/samples/snippets/test_site_key.py b/samples/snippets/test_site_key.py new file mode 100644 index 0000000..1cc85c8 --- /dev/null +++ b/samples/snippets/test_site_key.py @@ -0,0 +1,65 @@ +# Copyright 2021 Google Inc. All Rights Reserved. +# +# 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 + +from _pytest.capture import CaptureFixture +import pytest + +from create_site_key import create_site_key +from delete_site_key import delete_site_key +from get_site_key import get_site_key +from list_site_keys import list_site_keys +from update_site_key import update_site_key + +# TODO(developer): Replace these variables before running the sample. +GOOGLE_CLOUD_PROJECT = os.environ["GOOGLE_CLOUD_PROJECT"] +DOMAIN_NAME = "localhost" + + +@pytest.fixture(scope="module") +def recaptcha_site_key() -> str: + recaptcha_site_key = create_site_key( + project_id=GOOGLE_CLOUD_PROJECT, domain_name=DOMAIN_NAME + ) + yield recaptcha_site_key + delete_site_key( + project_id=GOOGLE_CLOUD_PROJECT, recaptcha_site_key=recaptcha_site_key + ) + + +def test_create_site_key(recaptcha_site_key: str) -> None: + assert len(recaptcha_site_key) != 0 + + +def test_list_site_keys(capsys: CaptureFixture, recaptcha_site_key: str) -> None: + list_site_keys(project_id=GOOGLE_CLOUD_PROJECT) + out, _ = capsys.readouterr() + assert re.search(f"keys/{recaptcha_site_key}", out) + + +def test_get_site_key(capsys: CaptureFixture, recaptcha_site_key: str) -> None: + get_site_key(project_id=GOOGLE_CLOUD_PROJECT, recaptcha_site_key=recaptcha_site_key) + out, _ = capsys.readouterr() + assert re.search(f"Successfully obtained the key !.+{recaptcha_site_key}", out) + + +def test_update_site_key(capsys: CaptureFixture, recaptcha_site_key: str) -> None: + update_site_key( + project_id=GOOGLE_CLOUD_PROJECT, + recaptcha_site_key=recaptcha_site_key, + domain_name=DOMAIN_NAME + ) + out, _ = capsys.readouterr() + assert re.search("reCAPTCHA Site key successfully updated ! ", out) diff --git a/samples/snippets/update_site_key.py b/samples/snippets/update_site_key.py new file mode 100644 index 0000000..8ee79a1 --- /dev/null +++ b/samples/snippets/update_site_key.py @@ -0,0 +1,85 @@ +# Copyright 2021 Google Inc. All Rights Reserved. +# +# 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 recaptcha_enterprise_update_site_key] +import time + +from google.cloud import recaptchaenterprise_v1 + + +def update_site_key(project_id: str, recaptcha_site_key: str, domain_name: str) -> None: + """ + Update the properties of the given site key present under the project id. + + Args: + project_id: GCloud Project ID. + recaptcha_site_key: Specify the site key. + domain_name: Specify the domain name for which the settings should be updated. + """ + + client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient() + + # Construct the key details. + key_name = f"projects/{project_id}/keys/{recaptcha_site_key}" + + # Set the name and the new settings for the key. + web_settings = recaptchaenterprise_v1.WebKeySettings() + web_settings.allow_amp_traffic = True + web_settings.allowed_domains.append(domain_name) + + key = recaptchaenterprise_v1.Key() + key.display_name = "any descriptive name for the key" + key.name = key_name + key.web_settings = web_settings + + update_key_request = recaptchaenterprise_v1.UpdateKeyRequest() + update_key_request.key = key + client.update_key(update_key_request) + + time.sleep(5) + + # Retrieve the key and check if the property is updated. + get_key_request = recaptchaenterprise_v1.GetKeyRequest() + get_key_request.name = key_name + response = client.get_key(get_key_request) + web_settings = response.web_settings + + # Get the changed property. + if not web_settings.allow_amp_traffic: + print( + "Error! reCAPTCHA Site key property hasn't been updated. Please try again !" + ) + else: + print("reCAPTCHA Site key successfully updated ! ") + + +# [END recaptcha_enterprise_update_site_key] + + +if __name__ == "__main__": + import google.auth + import google.auth.exceptions + + # TODO(developer): Replace the below variables before running + try: + default_project_id = google.auth.default()[1] + recaptcha_site_key = "recaptcha_site_key" + domain_name = "localhost" + except google.auth.exceptions.DefaultCredentialsError: + print( + "Please use `gcloud auth application-default login` " + "or set GOOGLE_APPLICATION_CREDENTIALS to use this script." + ) + else: + update_site_key(default_project_id, recaptcha_site_key, domain_name)