Skip to content

Commit 69047a6

Browse files
Sita04gcf-owl-bot[bot]partheasai-sunder-s
authored
docs(samples): add auth samples and tests (#1102)
* docs(samples): add auth samples and tests * refactored verifying google token and lint fixed test file * Modified comment acc to review * renamed method acc to review comment * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * 🦉 Updates from OwlBot post-processor See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * added comment acc to review * add samples tests as required checks * use GOOGLE_CLOUD_PROJECT * test new config 1 * adding refresh token for sys test * updating all py verion configs * update 3 * update 4 * update 5 - trimming nox * update 6 - fixing requirements.txt * update 7 - fixing pytest flags * update 8 - fixing sa test cred * update 9- reading sa path from env * update 10- testing explicit * update 11 - fix multi reference * update 12 - remove project id from client params * update 13 - use projectid from default * update 14 - remove project param * update 15- fix assert * update 16 - updating other py versions * update 17: try replacing compute with storage * update 18: fix assert and pass project * update 19: fixing comments * update 20: remove unused Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com> Co-authored-by: Anthonios Partheniou <partheniou@google.com> Co-authored-by: Sai Sunder Srinivasan <saisunder@google.com>
0 parents  commit 69047a6

10 files changed

Lines changed: 505 additions & 0 deletions
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# Copyright 2022 Google Inc.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
# [START auth_cloud_explicit_adc]
16+
17+
from google.cloud import storage
18+
19+
import google.oauth2.credentials
20+
import google.auth
21+
22+
23+
def authenticate_explicit_with_adc():
24+
"""
25+
List storage buckets by authenticating with ADC.
26+
27+
// TODO(Developer):
28+
// 1. Before running this sample,
29+
// set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
30+
// 2. Replace the project variable.
31+
// 3. Make sure you have the necessary permission to list storage buckets: "storage.buckets.list"
32+
"""
33+
34+
# Construct the Google credentials object which obtains the default configuration from your
35+
# working environment.
36+
# google.auth.default() will give you ComputeEngineCredentials
37+
# if you are on a GCE (or other metadata server supported environments).
38+
credentials, project_id = google.auth.default()
39+
# If you are authenticating to a Cloud API, you can let the library include the default scope,
40+
# https://www.googleapis.com/auth/cloud-platform, because IAM is used to provide fine-grained
41+
# permissions for Cloud.
42+
# If you need to provide a scope, specify it as follows:
43+
# credentials = google.auth.default(scopes=scope)
44+
# For more information on scopes to use,
45+
# see: https://developers.google.com/identity/protocols/oauth2/scopes
46+
47+
# Construct the Storage client.
48+
storage_client = storage.Client(credentials=credentials, project=project_id)
49+
buckets = storage_client.list_buckets()
50+
print("Buckets:")
51+
for bucket in buckets:
52+
print(bucket.name)
53+
print("Listed all storage buckets.")
54+
55+
# [END auth_cloud_explicit_adc]
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Copyright 2022 Google Inc.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
# [START auth_cloud_implicit_adc]
16+
17+
from google.cloud import storage
18+
19+
20+
def authenticate_implicit_with_adc(project_id="your-google-cloud-project-id"):
21+
"""
22+
When interacting with Google Cloud Client libraries, the library can auto-detect the
23+
credentials to use.
24+
25+
// TODO(Developer):
26+
// 1. Before running this sample,
27+
// set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
28+
// 2. Replace the project variable.
29+
// 3. Make sure that the user account or service account that you are using
30+
// has the required permissions. For this sample, you must have "storage.buckets.list".
31+
Args:
32+
project_id: The project id of your Google Cloud project.
33+
"""
34+
35+
# This snippet demonstrates how to list buckets.
36+
# *NOTE*: Replace the client created below with the client required for your application.
37+
# Note that the credentials are not specified when constructing the client.
38+
# Hence, the client library will look for credentials using ADC.
39+
storage_client = storage.Client(project=project_id)
40+
buckets = storage_client.list_buckets()
41+
print("Buckets:")
42+
for bucket in buckets:
43+
print(bucket.name)
44+
print("Listed all storage buckets.")
45+
46+
# [END auth_cloud_implicit_adc]
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# Copyright 2022 Google Inc.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
# [auth_cloud_idtoken_impersonated_credentials]
16+
17+
import google
18+
from google.auth import impersonated_credentials
19+
import google.auth.transport.requests
20+
21+
22+
def idtoken_from_impersonated_credentials(
23+
impersonated_service_account: str, scope: str, target_audience: str):
24+
"""
25+
Use a service account (SA1) to impersonate as another service account (SA2) and obtain id token
26+
for the impersonated account.
27+
To obtain token for SA2, SA1 should have the "roles/iam.serviceAccountTokenCreator" permission
28+
on SA2.
29+
30+
Args:
31+
impersonated_service_account: The name of the privilege-bearing service account for whom the credential is created.
32+
Examples: name@project.service.gserviceaccount.com
33+
34+
scope: Provide the scopes that you might need to request to access Google APIs,
35+
depending on the level of access you need.
36+
For this example, we use the cloud-wide scope and use IAM to narrow the permissions.
37+
https://cloud.google.com/docs/authentication#authorization_for_services
38+
For more information, see: https://developers.google.com/identity/protocols/oauth2/scopes
39+
40+
target_audience: The service name for which the id token is requested. Service name refers to the
41+
logical identifier of an API service, such as "iap.googleapis.com".
42+
Examples: iap.googleapis.com
43+
"""
44+
45+
# Construct the GoogleCredentials object which obtains the default configuration from your
46+
# working environment.
47+
credentials, project_id = google.auth.default()
48+
49+
# Create the impersonated credential.
50+
target_credentials = impersonated_credentials.Credentials(
51+
source_credentials=credentials,
52+
target_principal=impersonated_service_account,
53+
# delegates: The chained list of delegates required to grant the final accessToken.
54+
# For more information, see:
55+
# https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-permissions
56+
# Delegate is NOT USED here.
57+
delegates=[],
58+
target_scopes=[scope],
59+
lifetime=300)
60+
61+
# Set the impersonated credential, target audience and token options.
62+
id_creds = impersonated_credentials.IDTokenCredentials(
63+
target_credentials,
64+
target_audience=target_audience,
65+
include_email=True)
66+
67+
# Get the ID token.
68+
# Once you've obtained the ID token, use it to make an authenticated call
69+
# to the target audience.
70+
request = google.auth.transport.requests.Request()
71+
id_creds.refresh(request)
72+
# token = id_creds.token
73+
print("Generated ID token.")
74+
75+
# [auth_cloud_idtoken_impersonated_credentials]
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Copyright 2022 Google Inc.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
# [START auth_cloud_idtoken_metadata_server]
16+
17+
import google
18+
import google.oauth2.credentials
19+
from google.auth import compute_engine
20+
import google.auth.transport.requests
21+
22+
23+
def idtoken_from_metadata_server(url: str):
24+
"""
25+
Use the Google Cloud metadata server in the Cloud Run (or AppEngine or Kubernetes etc.,)
26+
environment to create an identity token and add it to the HTTP request as part of an
27+
Authorization header.
28+
29+
Args:
30+
url: The url or target audience to obtain the ID token for.
31+
Examples: http://www.abc.com
32+
"""
33+
34+
request = google.auth.transport.requests.Request()
35+
# Set the target audience.
36+
# Setting "use_metadata_identity_endpoint" to "True" will make the request use the default application
37+
# credentials. Optionally, you can also specify a specific service account to use by mentioning
38+
# the service_account_email.
39+
credentials = compute_engine.IDTokenCredentials(
40+
request=request, target_audience=url, use_metadata_identity_endpoint=True
41+
)
42+
43+
# Get the ID token.
44+
# Once you've obtained the ID token, use it to make an authenticated call
45+
# to the target audience.
46+
credentials.refresh(request)
47+
# print(credentials.token)
48+
print("Generated ID token.")
49+
50+
# [END auth_cloud_idtoken_metadata_server]
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# Copyright 2022 Google Inc.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
# [START auth_cloud_idtoken_service_account]
16+
17+
import google.auth
18+
import google.auth.transport.requests
19+
20+
from google.oauth2 import service_account
21+
22+
23+
def get_idToken_from_serviceaccount(json_credential_path: str, target_audience: str):
24+
"""
25+
TODO(Developer): Replace the below variables before running the code.
26+
27+
*NOTE*:
28+
Using service account keys introduces risk; they are long-lived, and can be used by anyone
29+
that obtains the key. Proper rotation and storage reduce this risk but do not eliminate it.
30+
For these reasons, you should consider an alternative approach that
31+
does not use a service account key. Several alternatives to service account keys
32+
are described here:
33+
https://cloud.google.com/docs/authentication/external/set-up-adc
34+
35+
Args:
36+
json_credential_path: Path to the service account json credential file.
37+
target_audience: The url or target audience to obtain the ID token for.
38+
Examples: http://www.abc.com
39+
"""
40+
41+
# Obtain the id token by providing the json file path and target audience.
42+
credentials = service_account.IDTokenCredentials.from_service_account_file(
43+
filename=json_credential_path,
44+
target_audience=target_audience)
45+
46+
request = google.auth.transport.requests.Request()
47+
credentials.refresh(request)
48+
print("Generated ID token.")
49+
50+
# [END auth_cloud_idtoken_service_account]

auth/cloud-client-temp/noxfile.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Copyright 2019 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import os
16+
import pathlib
17+
import shutil
18+
19+
import nox
20+
21+
CURRENT_DIRECTORY = pathlib.Path(__file__).parent.absolute()
22+
23+
# https://github.com/psf/black/issues/2964, pin click version to 8.0.4 to
24+
# avoid incompatiblity with black.
25+
CLICK_VERSION = "click==8.0.4"
26+
BLACK_VERSION = "black==19.3b0"
27+
BLACK_PATHS = [
28+
"google",
29+
"tests",
30+
"tests_async",
31+
"noxfile.py",
32+
"setup.py",
33+
"docs/conf.py",
34+
]
35+
36+
@nox.session(python=["3.7", "3.8", "3.9", "3.10"])
37+
def unit(session):
38+
# constraints_path = str(
39+
# CURRENT_DIRECTORY / "testing" / f"constraints-{session.python}.txt"
40+
# )
41+
session.install("-r", "requirements.txt")
42+
# session.install("-e", ".")
43+
session.run(
44+
"pytest",
45+
f"--junitxml=unit_{session.python}_sponge_log.xml",
46+
"snippets_test.py",
47+
# "tests_async",
48+
)
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Copyright 2022 Google LLC
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
# Default TEST_CONFIG_OVERRIDE for python repos.
16+
17+
# You can copy this file into your directory, then it will be inported from
18+
# the noxfile.py.
19+
20+
# The source of truth:
21+
# https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/noxfile_config.py
22+
23+
TEST_CONFIG_OVERRIDE = {
24+
# You can opt out from the test for specific Python versions.
25+
"ignored_versions": ["2.7"],
26+
# Old samples are opted out of enforcing Python type hints
27+
# All new samples should feature them
28+
"enforce_type_hints": True,
29+
# An envvar key for determining the project id to use. Change it
30+
# to 'BUILD_SPECIFIC_GCLOUD_PROJECT' if you want to opt in using a
31+
# build specific Cloud project. You can also use your own string
32+
# to use your own Cloud project.
33+
# "gcloud_project_env": "GOOGLE_CLOUD_PROJECT",
34+
"gcloud_project_env": "GOOGLE_CLOUD_PROJECT",
35+
# A dictionary you want to inject into your test. Don't put any
36+
# secrets here. These values will override predefined values.
37+
"envs": {},
38+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
google-cloud-compute==1.3.2
2+
google-cloud-storage==2.3.0
3+
google-auth==2.10.0
4+
pytest==7.1.2

0 commit comments

Comments
 (0)