Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.10/site-packages/google/auth/iam.py: 50%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# Copyright 2017 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.
15"""Tools for using the Google `Cloud Identity and Access Management (IAM)
16API`_'s auth-related functionality.
18.. _Cloud Identity and Access Management (IAM) API:
19 https://cloud.google.com/iam/docs/
20"""
22import base64
23import http.client as http_client
24import json
26from google.auth import _exponential_backoff
27from google.auth import _helpers
28from google.auth import credentials
29from google.auth import crypt
30from google.auth import exceptions
32IAM_RETRY_CODES = {
33 http_client.INTERNAL_SERVER_ERROR,
34 http_client.BAD_GATEWAY,
35 http_client.SERVICE_UNAVAILABLE,
36 http_client.GATEWAY_TIMEOUT,
37}
39_IAM_SCOPE = ["https://www.googleapis.com/auth/iam"]
41_IAM_ENDPOINT = (
42 "https://iamcredentials.googleapis.com/v1/projects/-"
43 + "/serviceAccounts/{}:generateAccessToken"
44)
46_IAM_SIGN_ENDPOINT = (
47 "https://iamcredentials.googleapis.com/v1/projects/-"
48 + "/serviceAccounts/{}:signBlob"
49)
51_IAM_IDTOKEN_ENDPOINT = (
52 "https://iamcredentials.googleapis.com/v1/"
53 + "projects/-/serviceAccounts/{}:generateIdToken"
54)
57class Signer(crypt.Signer):
58 """Signs messages using the IAM `signBlob API`_.
60 This is useful when you need to sign bytes but do not have access to the
61 credential's private key file.
63 .. _signBlob API:
64 https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts
65 /signBlob
66 """
68 def __init__(self, request, credentials, service_account_email):
69 """
70 Args:
71 request (google.auth.transport.Request): The object used to make
72 HTTP requests.
73 credentials (google.auth.credentials.Credentials): The credentials
74 that will be used to authenticate the request to the IAM API.
75 The credentials must have of one the following scopes:
77 - https://www.googleapis.com/auth/iam
78 - https://www.googleapis.com/auth/cloud-platform
79 service_account_email (str): The service account email identifying
80 which service account to use to sign bytes. Often, this can
81 be the same as the service account email in the given
82 credentials.
83 """
84 self._request = request
85 self._credentials = credentials
86 self._service_account_email = service_account_email
88 def _make_signing_request(self, message):
89 """Makes a request to the API signBlob API."""
90 message = _helpers.to_bytes(message)
92 method = "POST"
93 url = _IAM_SIGN_ENDPOINT.replace(
94 credentials.DEFAULT_UNIVERSE_DOMAIN, self._credentials.universe_domain
95 ).format(self._service_account_email)
96 headers = {"Content-Type": "application/json"}
97 body = json.dumps(
98 {"payload": base64.b64encode(message).decode("utf-8")}
99 ).encode("utf-8")
101 retries = _exponential_backoff.ExponentialBackoff()
102 for _ in retries:
103 self._credentials.before_request(self._request, method, url, headers)
105 response = self._request(url=url, method=method, body=body, headers=headers)
107 if response.status in IAM_RETRY_CODES:
108 continue
110 if response.status != http_client.OK:
111 raise exceptions.TransportError(
112 "Error calling the IAM signBlob API: {}".format(response.data)
113 )
115 return json.loads(response.data.decode("utf-8"))
116 raise exceptions.TransportError("exhausted signBlob endpoint retries")
118 @property
119 def key_id(self):
120 """Optional[str]: The key ID used to identify this private key.
122 .. warning::
123 This is always ``None``. The key ID used by IAM can not
124 be reliably determined ahead of time.
125 """
126 return None
128 @_helpers.copy_docstring(crypt.Signer)
129 def sign(self, message):
130 response = self._make_signing_request(message)
131 return base64.b64decode(response["signedBlob"])